Subtype union types with full intellisense with a type function
typescript javascript typesIf you want to create a subtype of a union type, but want intellisense and type checking to work both while creating the type and while using it, you'll need to create a type function:
type Extends<T, U extends T> = U
Object keys are a union type. You might want to create a subtype for a specific, partial list of keys from the object, which you want to treat differently. Below you see an example where this Extends
type function is used to make sure that you can only create the subtype with types from the union.
type Extends<T, U extends T> = U;
type Special = string
type DataTransferObject = {
normalKey1: string;
normalKey2: number;
specialKey1: Special;
specialKey2: Special;
};
type ValidSubtype = Extends<
keyof DataTransferObject,
"specialKey1" | "specialKey2"
>;
// Error
type InvalidSubtype = Extends<
keyof DataTransferObject,
"specialKey1" | "specialKey2" | "zcvz"
>;
const validUsage: Set<ValidSubtype> = new Set(["specialKey1", "specialKey2"]);
// Error
const invalidUsage: Set<ValidSubtype> = new Set(["specialKey1", "asdasd"]);
Play with this example on the typescript playground
Source: Stack overflow