Answer the question
In order to leave comments, you need to log in
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 один из ключей не совпадает
Answer the question
In order to leave comments, you need to log in
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 один из ключей не совпадает
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question