Skip to main content

Basic Prop Types in TypeScript

In TypeScript, we can define the shape of an object using interfaces or types.

This is particularly useful in scenarios where you want to ensure the objects have a certain set of properties with specific types.

Let’s explore some examples:

Enumerations

Enumerations, or enum, are a special kind of type in TypeScript used for defining a collection of related values. Here’s an example:

export enum Gender {
Female = 'female',
Male = 'male',
Other = 'other'
}

In this example, Gender is an enumeration that can take one of three values: ‘female’, ‘male’, or ‘other’.

Interfaces

Interfaces in TypeScript allow you to define the shape of an object. Here’s an example:

export interface Diagnose {
code: string;
name: string;
latin?: string;
}

In this example, Diagnose is an interface that describes an object with properties code, name, and latin. The latin property is optional, as indicated by the ?.

Union Types

Union types are a powerful way to express a variable with multiple types. Here’s an example:

export type Entry =
| HospitalEntry
| OccupationalHealthcareEntry
| HealthCheckEntry;

In this example, Entry is a union type that can be any one of HospitalEntry, OccupationalHealthcareEntry, or HealthCheckEntry.

Utility Types

Utility types in TypeScript provide convenient transformations on types. Here’s an example:



type UnionOmit<T, K extends string | number | symbol>
= T extends unknown ?
Omit<T, K>
: never;

export type NoSsnPatient = Omit<Patient, 'ssn'>;

export type EntryWithoutId = UnionOmit<Entry, 'id'>;

In this example, NoSsnPatient is a utility type that represents a Patient type but without the ssn property.