MaximilianMairinger
MaximilianMairinger

Reputation: 2424

typescript: Infer tuple value at index from usage

How do you infer a Value of a tuple at a specific from usage index.

class A<T extends any[]> {
  constructor(public a: T[0]) {

  }
}

// a should be A<[number]>
let a = new A(2)
// but is A<any[]>

This is what I am looking for. Is the above described functionality somehow possible?

Upvotes: 0

Views: 137

Answers (1)

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20043

You can explictily specify the type argument which will type-check:

const a1 = new A<[number]>(2); // ok
const a2 = new A<[number]>('Oops'); // error 

Automatically inferring the type like this is not possible, I think. However, if you only care about the first value in the array (as in your example), something like this would be possible:

class A<U, T extends [U, ...any[]]> { 
  constructor(public a: U) { }
}

const a = new A(2); // A<number, [number, ...any[]]>

Or, sticking with your original definition, you could go through a static factory method:

class A<T extends any[]> {
  constructor(public a: T[0]) {
  }

  static create<U>(a: U): A<[U]> { 
    return new A(a);
  }
}

const a = A.create(2); // A<[number]>

Upvotes: 2

Related Questions