https://www.typescriptlang.org/docs/handbook/utility-types.html
- Partial
: useful for update react component state via setter - Required
: all fields are set to required, useful to reinforce fields - Readonly
: all fields are set to readonly
- Record<Keys, Type>: map the properties of a type to another type
- Pick<Type, Keys>, Omit<Type, Keys>: include/ not include some properties of a type
- Exclude<UnionType, ExcludedMembers>: exclude all union members assignable to
ExcludedMembers
. e.g.type T = Exclude<string | number | (() => void), Function>
,type T = string } number
- Extract<Type, Union>, all types assignable to
Union
, e.g.type T = Extract<string | number | (() => void), Function>
,type T = () => void
- NonNullable
: extract null
andundefined
- Parameters
: Type
needs to satisfy the constraint(...args:any) => any
, andParameters<Type>
will be type of args - ConstructorParameters
- ReturnType
- InstanceType
: type of a class’s instance - ThisParameterType
OmitThisParameter
ThisType
Intrinsic String Manipulation Types
- Uppercase
- Lowercase
- Capitalize
- Uncapitalize
Interesting examples
1 | // ThisParameterType |
1 | // remove this parameter via bind |
Intersection type & ThisType unity
1 | // Intersection type, ThisType unity |
When type D = { x: number; y: number }
and type M = { moveBy: (dx: number, dy: number) => void }
, type D & M
is { x: number, y: number } & { moveBy(dx: number, dy: number): number }
.
The methods
object in the argument to makeObject
has a contextual type that includes ThisType<D & M>
and therefore the type of this
in methods within the methods
object is { x: number, y: number } & { moveBy(dx: number, dy: number): number }
Notice how the type of the methods
property simultaneously is an inference target and a source for the this
type in methods.