Search code examples
typescripttypescript-generics

Typescript: enforce narrow inferred generic for all inputs of a function


Say I have a way of defining vectors (a 1-dimensional list of numbers) where the length of the vector is a generic:

interface Vector<LengthT extends number> {
  length: LengthT,
  data: number[]
}

We can create a vector where the type system is aware of its length:

const vector2a: Vector<2> = { length: 2, data: [1, 2] }

Then, we create a function where we want to only accept vectors of identical length:

// This isn't restrictive enough
function addAll<LengthT extends number>(...vectors: Vector<LengthT>[]) {
  // construct a new Vector<LengthT> based on element-wise addition
}

// this should be allowed
const vector2Sum = addAll(vector2a, vector2b, vector2c)

// this should be disallowed
const vector2badSum = addAll(vector2a, vector3)

Is it possible to restrict inputs to this addAll function to have identical values of LengthT?

Playground link.


Solution

  • You can use NoInfer to infer the length from the first argument only:

    Playground

    function addAll<LengthT extends number>(...vectors: [Vector<LengthT>, ...Vector<NoInfer<LengthT>>[]] ) {
      // construct a new Vector<LengthT> based on element-wise addition
    }