instantiate class in typescript

2020-04-10

 | 

~1 min read

 | 

199 words

Tonight, had a real head scratcher: how to instantiate a class in Typescript that uses a constructor without a compiler error!

In Vanilla JS, this works just fine:

person.js
export class Person {
  constructor(name: string) {
    this.name = name
  }
  age = 0
  setAge(age: number) {
    this.age = age
  }
}

let joe = new Person("joe")
joe.setAge(22)
console.log(joe.name, joe.age) // joe 22

But, if you were to use this in Typescript, the compiler would yell, saying name does not exist on type 'Person'.

I’ll admit, I was stumped for a while.

person.ts
export class Person {
  name = ""  constructor(name: string) {
    this.name = name
  }
  age = 0
  public setAge(age: number) {
    this.age = age
  }
}

let joe = new Person("joe")
joe.setAge(22)
console.log(joe.name, joe.age) // joe 22

The solution is simple in the end, albeit certainly unintuitive to me - Add a default value and then override that value within the constructor!

Here’s a CodeSandbox to prove the point.

Sometimes solutions are simpler than I give them credit for - though if anyone has a better way to do this, or a rationale for what’s happening here that I’m missing, I’m all ears!



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!