TypeScript - Advanced templates
When creating generic functionality, the complexity of the result type of the operation can increase. There are a few techniques that enable you to handle specific scenarios when the result type varies widely for different types of input.
Use these utilities to fully harness the power of TypeScript!
Infer keyword
I know that I can use the infer keyword inside conditional types to declaratively introduce a new generic type variable.
I also know how to apply this mechanism to array items or function type elements.
Mapping modifiers
I know how to use the in keyof syntax to create a generic object type based on an existing object type while applying modifications using, for example, the +
and -
operators.
Key remapping and template literal types
I know that I can remap keys using the in keyof ... as ...
syntax. I also know that I can use template literal types to apply transformations to the keys, such as adding prefixes or capitalizing them, and so on
Distributive conditional types
I know that I can disable the distributivity of union types by surrounding each side of the extends keyword with square brackets.
I know that I can use the infer keyword inside conditional types to declaratively introduce a new generic type variable.
I also know how to apply this mechanism to array items or function type elements.
I know how to use the in keyof syntax to create a generic object type based on an existing object type while applying modifications using, for example, the +
and -
operators.
I know that I can remap keys using the in keyof ... as ...
syntax. I also know that I can use template literal types to apply transformations to the keys, such as adding prefixes or capitalizing them, and so on
I know that I can disable the distributivity of union types by surrounding each side of the extends keyword with square brackets.