TypeScript 相关
Published by powerflyang on Jul 18, 2022
Useful TypeScript features:
- infer
- never
- keyof + in
infer
The infer
keyword allows you to deduce a type from another type within a conditional type.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
const User = { id: 123, username: 'John', email: 'john@gmail.com', addons: [ { name: 'WriteAddon', id: 1 }, { name: 'TodoAddon', id: 2 } ] }; type UnpackArray<T> = T extends (infer R)[] ? R: T; type AddonType = UnpackArray<typeof User.addons>; // { name: string, id: number }
never
The never
type represents a value that is never observed.
In a return type, this means that the function throws an exception or terminates the execution of the program.
keyof + in
1 2 3
type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]>; };