I want to create union type from brother of same interface
like below
interface Foo {
values: string[];
defaultValue: string;
}
function fooo({values, defaultValue}: Foo) {}
fooo({values: ['a', 'b'], defaultValue: 'a'}); // this is correct example
fooo({values: ['a', 'b'], defaultValue: 'c'}); // I want to prevent this case!
// defaultValue must be 'a' or 'b'
// like tuple type 'a' | 'b'
Can I do this?
CodePudding user response:
Sure, you can achieve this by adding generic types.
interface Foo<K extends string[]> {
values: [...K];
defaultValue: K[number];
}
function fooo<K extends string[]>({values, defaultValue}: Foo<K>) {}
The generic type K
will the tuple type of the value
array. We then constrain defaultValue
to only have the values specified in values
with K[number]
.
Let's see if it works:
fooo({values: ['a', 'b'], defaultValue: 'a'});
fooo({values: ['a', 'b'], defaultValue: 'c'}); // error: Type '"c"' is not assignable to type '"a" | "b"'