Mister_L
Mister_L

Reputation: 2611

typescript - class as interface when constructor is used

If I have a class of this form:

class MyClass {
   a: string  
}

and then I define a variable:

let obj: MyClass = { a: 2 }

I'm getting a Typescript error, as expected, because 2 is not a string. However, if MyClass contains a constructor:

class MyClass {
   constructor(a: string) {
   }
}

Then Typescript remains silent after the same variable declaration. Is there a way to use a constructor and still use the class as interface? Thanks.

Upvotes: 0

Views: 85

Answers (2)

Josean
Josean

Reputation: 1

let obj: MyClass = { a: 2 }

You are giving the class the integer 2.

What you're trying to do is

let obj: MyClass = { a: '2' }

The other comment explained it pretty well.

Upvotes: 0

kingdaro
kingdaro

Reputation: 12028

TypeScript remains silent because the second example of MyClass doesn't define any member variable for a, only a constructor argument. You'll still have to declare the member variable in order for it to be checked:

class MyClass {
  a: string

  constructor(a: string) {
    this.a = a // assign to self as an example
  }
}

However, TS gives some nice syntactic sugar for this. If you put an access visibility keyword like public, private or protected in front of the constructor argument, typescript will automatically assign it for you, with that level of visibility. So this becomes equivalent to the above, which is what I think you might've wanted to do here.

class MyClass {
  constructor(public a: string) {}
}

Upvotes: 4

Related Questions