Type Alias: ExtractField<T, K>
ExtractField<
T
,K
>:T
extendsRecord
<K
, infer U> ?U
:never
ExtractField is a utility type that extracts the type of a specific field from a type T
.
This type takes two parameters:
T
, the type from which the field type is to be extracted.K
, the key of the field to be extracted fromT
.
The utility type works as follows:
-
T extends Record<K, infer U>
: This conditional check verifies ifT
can be assigned to a record type with a keyK
and some value. If it can, TypeScript infers the type of this value and assigns it toU
. -
U
is returned whenT
is assignable toRecord<K, infer U>
, i.e., whenT
has the keyK
. -
If
T
does not have the keyK
, the utility type returnsnever
.
This utility type is powerful as it allows the extraction of a specific field's type dynamically, given the field's name. It is useful when working with complex and dynamic types where the structure might not be known ahead of time.
Type Parameters
Type Parameter |
---|
T |
K extends keyof any |