A
A
Artem2020-09-23 20:32:35
typescript
Artem, 2020-09-23 20:32:35

How to type an array of interface keys?

interface Interface {
  foo: boolean;
  bar: string;
  baz: object
}

type Keys = KeysOfInterface<Interface>;

let keys: Keys;

keys = ['foo', 'bar', 'baz']; // OK все ключи указаны
keys = ['foo']; // NOT OK указаны не все ключи
keys = ['foo', 'bar', 'another bar']; // NOT OK один из ключей не совпадает


keyof returns a Union of keys and doesn't throw an exception if one of the values ​​is missing

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-09-23
@Aetae

There are several solutions here.
For example:

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

interface Interface {
  foo: boolean;
  bar: string;
  baz: object
}

type Keys = TupleUnion<keyof Interface>; 

let keys: Keys;

keys = ['foo', 'bar', 'baz']; // OK все ключи указаны
keys = ['foo']; // NOT OK указаны не все ключи
keys = ['foo', 'bar', 'another bar']; // NOT OK один из ключей не совпадает

But in a real project, it is highly not recommended to use them - they will gobble up all the memory and the entire processor for you if there are more than a couple of keys.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question