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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With