typescripttypescript-genericstypescript4.0

TypeScript: Infer parameter values from constructor and use it as type checking on class method's parameter


Not sure if this is possible, but I'm looking for a way to allow TypeScript to automatically infer a class constructor's argument values, then use the inferred values to type-check another parameter of a class method.

For example:

class MyClass {
  // aim: to infer the string values from the rest parameter param2
  constructor(param1: number, ...param2: string[]) {
    console.log(param1);
    console.log(param2);
  }

  // param uses values inferred from param2
  classMethod(param) {
    console.log(param);
  }
}

The aim is to allow TypeScript to infer values from param2 then apply it onto classMethod's param. For example:

const myClass = new MyClass( 0, 'a', 'b', 'c' );
myClass.classMethod('a') // shall be correct
myClass.classMethod('x') // TypeScript shall highlight this with red wavy line

I've tried using generic, but ultimately confused on how to infer values from generic T which extends a string array. For example:

class MyClass<T extends string[] = []> {
  constructor(param1: number, ...param2: T) {
    // things
  }

  // how do I infer the array values in T?
  classMethod(param) {
    console.log(param);
  }
}

Perhaps I'm still lacking of some steps to correctly infer the values from the generic. Will this be possible? Thank you in advance!


Solution

  • Many thanks @jonrsharpe, it was an oversight on my end on the generic part. I will mark this question as answered with your answer.

    Here's the correct answer as written by @jonrsharpe:

    class MyClass<T extends string> {
      constructor(param1: number, ...param2: T[]) {
        // things
      }
    
      classMethod(param: T) {
        console.log(param);
      }
    }
    
    const myClass = new MyClass( 0, 'a', 'b', 'c' );
    myClass.classMethod('a') // correct
    myClass.classMethod('x') // error
    

    TypeScript Playground