0
type ValidValue = 'X' | 'Y';

type MyType = {
   arr: ValidValue[];
}

How to enforce arr to have as max length N (2 in this case, because we have 2 valid distinct values)

2
  • So is ['X', 'X'] acceptable or not? Commented Aug 24, 2021 at 18:20
  • @jcalz no, actually. they should not be repeated. Commented Aug 25, 2021 at 6:56

3 Answers 3

2

Typescript has fixed size array which called as tuple you can use optional element in tuple like this

let t: [number, string?, boolean?];
t = [42, "hello", true];
t = [42, "hello"];
t = [42];

also, this answer had more details about fixed-size arrays and you can find about typescript Types in here.

Sign up to request clarification or add additional context in comments.

2 Comments

I edited the question to specify that I meant distinct values. is it possible to improve your answer based on that?
in that case, you can use SET data structure which can store distinct values like List " const x = new Set<ValidValue>() " refer this javatpoint.com/typescript-set
1

You can make use of tuple type like this:

type ValidValue = 'X' | 'Y';

type MyType = {
   arr: [ValidValue, ValidValue];
}

const obj :MyType = {
    arr: ['X', 'Y']  // <--- valid
}

const obj2 :MyType = {
    arr: ['X', 'Y', 'Y']  // <--- error
}

Playground

4 Comments

Is it still valid with a single element?
What did you mean by single element? like [string,string]?
The OP said How to enforce arr to have as max length N - if max length of the array is 2, that implies that you could have an array of length 1. [<element>]
I found this answer: stackoverflow.com/questions/65495285/… so if you need to also allow less-than-N length arrays, you could do arr: [ValidValue?, ValidValue?];
0

Since array is an Object in Javascript you can extend the type using the intersection (&) to ensure the length of the array:

type ValidValue = 'X' | 'Y';

type MyType = {
   arr: ValidValue[] & { length: 2 };
}

This does however not prevent duplicated values in the array like ['X', 'X']

Comments

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.