0

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.

0

2 Answers 2

4

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) {}
}
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, the public modifier is the missing part, thanks.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.