Home > database >  Get class property types for constructor arguments
Get class property types for constructor arguments

Time:03-05

I'm looking to somehow reference a class's property's type in the constructor because I'm finding myself writing out pretty complex types when I feel there should be a simpler way.

class Foo {
  size : string
  constructor (size : typeof this.size /* doesn't work */) {
    this.size = size
  }
}

CodePudding user response:

To refer to the type of a property, you can use Type["property"], in this case:

class Foo {
  size: string;

  constructor(size: Foo["size"]) {
    this.size = size
  }
}

But TypeScript also gives a shorthand for parameter properties, so you can write the whole thing as:

class Foo {
  constructor(public size: string) {}
}

You can see in this playground that the same JS is generated either way.

  • Related