Last active
August 31, 2021 15:58
-
-
Save eamonnboyle/10ab2ed3d35308ca0d28372659455f70 to your computer and use it in GitHub Desktop.
Type Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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