Created
September 9, 2019 22:12
-
-
Save IvanTorresEdge/0e68b119c1b33264c70b6d8b009d5eeb to your computer and use it in GitHub Desktop.
Useful TypeScript Snippets
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
/** | |
* Recursively convert any data structure to readonly (with handling of privimitives): | |
*/ | |
type DeepReadonlyObject<T> = { readonly [K in keyof T]: DeepReadonly<T[K]> }; | |
type DeepReadonly<T> = T extends (infer E)[] | |
? ReadonlyArray<DeepReadonlyObject<E>> | |
: T extends object ? DeepReadonlyObject<T> : T; | |
/** | |
* Example Usage: | |
*/ | |
interface IRecipient { | |
email: string; | |
name: string; | |
} | |
interface IEmail { | |
body: string; | |
recipients: IRecipient[]; | |
} | |
type IReadonlyEmail = DeepReadonly<IEmail>; | |
const myEmail: IReadonlyEmail = { | |
body: "Hello", | |
recipients: [ | |
{ | |
email: "jhon.doe@example.net", | |
name: "John Doe" | |
} | |
] | |
}; | |
/** | |
* The following line throws a compilation error: | |
*/ | |
myEmail.body = "Hello John!"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment