Skip to content

Instantly share code, notes, and snippets.

@eamonnboyle
Last active August 31, 2021 15:58
Show Gist options
  • Save eamonnboyle/10ab2ed3d35308ca0d28372659455f70 to your computer and use it in GitHub Desktop.
Save eamonnboyle/10ab2ed3d35308ca0d28372659455f70 to your computer and use it in GitHub Desktop.
Type Programming
interface Employee {
name: string;
age: number;
dob: Date;
}
// Type Intersection
type EmployeeWithId = Employee & { id: string };
// This type will be equivalent to
// {
// id: string;
// name: string;
// age: number;
// dob: Date;
// }
// Readonly uses Mapped Types
type ReadonlyEmployee = Readonly<Employee>;
// This type will be equivalent to
// {
// readonly name: string;
// readonly age: number;
// readonly dob: Date;
// }
// A Mapped Type with a Conditional Type allows for interesting transformations
type DateToString<T> = {
[P in keyof T]: T[P] extends Date ? string : T[P];
};
type EmployeeJson = DateToString<Employee>
// This type will be equivalent to
// {
// name: string;
// age: number;
// dob: string; // Date has changed to string
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment