2

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?

4
  • So only those two combinations are valid? Commented Nov 30, 2022 at 10:39
  • 3
    See this Commented Nov 30, 2022 at 10:42
  • 1
    this answer is related, however it also allows less elements Commented Nov 30, 2022 at 10:43
  • 1
    There is also this: tsplay.dev/WYRv2w. It checks if all elements are present, although doubled elements are allowed. Has the advantage of not being combinatory explosive. Commented Nov 30, 2022 at 10:49

1 Answer 1

0

You can do it by this way:

type MyType = [string, string];
Sign up to request clarification or add additional context in comments.

1 Comment

this doesn't restrict the string to being 'a' and 'b' it could literally be anything. captain-yossarian from Ukraine answer in the comments should be sufficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.