2

How do you get a union of constructor args in a class?

Assume we have

class Person {
   constructor(name: string, age: number){}
}

How would you get the type 'name' | 'age' ?

I have tried using

type ConstructorParametersOfPerson = ConstructorParameters<typeof Person>;

but this returns a tuple of the object [name: string, age: number] and e.g, using ConstructorParametersOfPerson[0] returns string and somehow throws the parameter key away.

Pavlo
  • 1,157
  • 7
  • 13
  • This is not possible. Parameter names are intentionally not observable in the type system. See the answers to the linked questions for more information, and the declined feature request at [ms/TS#31627](https://github.com/microsoft/TypeScript/issues/31627). – jcalz Jul 08 '22 at 18:46
  • So is it essentially IntelliSense that keeps track of the variable names? – Pavlo Jul 08 '22 at 19:29
  • More or less. The information is in the type's "quick info" (which is shown in IntelliSense) but is not available as a string literal. Type predicates like `(x: X) => x is Y` allow you to refer to parameter names, but they are just dummy names... there's no difference between that type and `(z: X) => z is Y`, so the names `x` and `z` are not really observable. – jcalz Jul 08 '22 at 19:35
  • That's quite useful to know. so my tuple was actually `[string, number]` but Intellij was just being nice – Pavlo Jul 08 '22 at 19:44

0 Answers0