Łukasz Karczewski
Łukasz Karczewski

Reputation: 1208

Ensure that two tuple arguments have the same number of elements

I want something like this:

function test(a: something, b: something) { ... }

test([1,2], [3,4])   // This is ok
test([1,2], [3,4,5]) // This is not ok. Arguments have different length. Should throw error
test([1,2,3,4,5], [6,7,8,9,10]) // This is ok too, the length itself doesn't matter, only equality

Is it possible somehow in TypeScript? I would like to change the something type to implement this, not during runtime.

Upvotes: 0

Views: 66

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25800

Do this:

  1. Make TypeScript treat the arguments as tuples by saying T extends unknown[] | [unknown]
  2. Put an extra constraint on b: T & { length: T['length'] }
declare function test<T extends unknown[] | [unknown]>(a: T, b: T & { length: T['length'] }): void;

Playground link

Upvotes: 2

Related Questions