Skip to content

Instantly share code, notes, and snippets.

@develax
Last active September 21, 2024 19:26
Show Gist options
  • Save develax/c669ef72eff4895485151bfaefcb19a3 to your computer and use it in GitHub Desktop.
Save develax/c669ef72eff4895485151bfaefcb19a3 to your computer and use it in GitHub Desktop.
Unions as type property keys

Unions

Unions as type property keys

type StringKeys = 'firstName' | 'lastName';
type NumberKeys = 'age';

type Person = {
    [Key in StringKeys]: string;
} & {
    [Key in NumberKeys]: number;
}

const person: Person = {
    age: 25,
    firstName: "Mary",
    lastName: "Poppins"
}

PLAYGROUND

Unions

type AlwaysString = string | never; // always 'string'
type StringOrNumber = string | number | never; // 'never' always loses
type Any = any | string | number | never; // 'any' always wins
type Unknown = unknown | string | number | never; // 'unknown' always wins
type Any2 = any | unknown | string | number | never; // 'any' wins 'unknown'

Conditional types and unions

/**
 * In the case of extending a union as a constraint, TypeScript will loop over each member of the union and return a union of its own.
 */
type NonOptional<T> = T extends null | undefined ? never : T;

type OptionalString = string | null | undefined;
type NonOptionalString = NonOptional<OptionalString>; // string

type OptionalManyTypes = string | boolean | number | null | undefined;
type NonOptionalManyTypes = NonOptional<OptionalManyTypes>; // string | number | boolean

PLAYGROUND

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment