Skip to content

Instantly share code, notes, and snippets.

@IvanTorresEdge
Created September 9, 2019 22:12
Show Gist options
  • Save IvanTorresEdge/0e68b119c1b33264c70b6d8b009d5eeb to your computer and use it in GitHub Desktop.
Save IvanTorresEdge/0e68b119c1b33264c70b6d8b009d5eeb to your computer and use it in GitHub Desktop.
Useful TypeScript Snippets
/**
* 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