I want to create a type that only accepts a specific combination of array values regardless of their order.
For example:
const acceptedCombo = ['a', 'b'];
function foo(param: MyType) {}
// Possible combos:
['a', 'b'] // OK
['b', 'a'] // OK
['a', 'b', 'c'] // TypeError - "c" is extra
['a'] // TypeError - "b" is missing
How can I define MyType
?
CodePudding user response:
You can do it by this way:
type MyType = [string, string];
CodePudding user response:
Here's the type which you can define:
type Type = [string, string]
const v1: Type = ['a', 'b'] // OK
const v2: Type = ['b', 'a'] // OK
const v3: Type = ['a', 'b', 'c'] // Type '[string, string, string]' is not assignable to type 'Type'
const v4: Type = ['a'] // Type '[string]' is not assignable to type 'Type'.