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)

dragonmnl
  • 14,578
  • 33
  • 84
  • 129

2 Answers2

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.

Buddhika Prasadh
  • 356
  • 1
  • 5
  • 16
  • I edited the question to specify that I meant distinct values. is it possible to improve your answer based on that? – dragonmnl Aug 25 '21 at 06:57
  • in that case, you can use SET data structure which can store distinct values like List " const x = new Set() " refer this https://www.javatpoint.com/typescript-set – Buddhika Prasadh Aug 25 '21 at 08:08
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

Ryan Le
  • 7,708
  • 1
  • 13
  • 23
  • Is it still valid with a single element? – TKoL Aug 26 '21 at 10:37
  • What did you mean by `single element`? like [string,string]? – Ryan Le Aug 26 '21 at 10:39
  • 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. `[]` – TKoL Aug 26 '21 at 12:03
  • I found this answer: https://stackoverflow.com/questions/65495285/typescript-restrict-maximum-array-length so if you need to also allow less-than-N length arrays, you could do `arr: [ValidValue?, ValidValue?];` – TKoL Aug 26 '21 at 12:04