Home > Blockchain >  Typescript - Type definition for an array of objects from union type
Typescript - Type definition for an array of objects from union type

Time:01-09

I want to create a type definition for an array of objects from a union or enum type. I want the type definition to fail if not all entries in the union exist in the array as a value of a key in the array of objects.

ts playground

export type SelectValue<T = any> = {
  value: T;
  label: string;
};

type options = "email" | "sms";

//ideally make this type check fail because it does not have all of the values of the options union
const values: SelectValue<options>[]  = [
    {
        value: "email",
        label: "Email",
    },
];

CodePudding user response:

TypeScript doesn't have a built-in type corresponding to an "exhaustive array" in which every member of some union type is guaranteed to exist somewhere in the array. Nor can you easily create your own specific type that works this way, at least not if the union has a lot of members in it or if you want to allow duplicates.

For a union with only a handful of members and if you want to prohibit duplicates, then you can could generate a union of all possible acceptable tuple types, like [SelectValue<"email">, SelectValue<"sms">] | [SelectValue<"sms">, SelectValue<"email">] for your example code (see here). But that scales very badly in the number

  • Related