Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Make sure an array contains all keys of an object constant

I have a const object (simulating enums). I want to take the keys of that object and put them in to an array. I want TypeScript to throw an error when one of them keys is missing from the array.

// My Enum.
export const Status = {
    'ACTIVE': 'Active',
    'DELETED': 'Deleted'
} as const;

// Enums keys and values.
export type StatusKeys = keyof typeof Status;
export type StatusValues = typeof Status[StatusKeys];

// I want TypeScript to recognise 'DELETED' is missing and throw an error.
// Ideally this will be done dynamically without the need to maintain another variable.
export const ArrayStatus: StatusKeys[] = ['ACTIVE'];

The idea behind it is that I will get errors any time I add or remove entries to that const object so I can update my code.

like image 914
Andrew Berridge Avatar asked Sep 06 '25 08:09

Andrew Berridge


1 Answers

If your after a union type, converted to array with typechecking.

Then this -> https://catchts.com/union-array might be what your after.

eg.

// My Enum.
export const Status = {
    'ACTIVE': 'Active',
    'DELETED': 'Deleted'
} as const;

// Enums keys and values.
export type StatusKeys = keyof typeof Status;
export type StatusValues = typeof Status[StatusKeys];

// I want TypeScript to recognise 'DELETED' is missing and throw an error.
// Ideally this will be done dynamically without the need to maintain another variable.

type TupleUnion<U extends string, R extends any[] = []> = {
    [S in U]: Exclude<U, S> extends never ? [...R, S] : TupleUnion<Exclude<U, S>, [...R, S]>;
}[U];

export const ArrayStatus: TupleUnion<StatusKeys> = ['ACTIVE', 'DELETED'];

export const ArrayStatusNoDelete: TupleUnion<Exclude<StatusKeys, 'DELETED'>> = ['ACTIVE']

TS Playground

like image 160
Keith Avatar answered Sep 07 '25 20:09

Keith