1

I’m struggling with TS constructors. Ill post this on stackoverflow, also.

Say you want to make the equivalent of these three constructors:

public Animal(){ this.name = “default”; this.noise =””; public Animal(string name){ this.name = name; this.noise = “”; } public Animal(string name, string noise){ this.name = name; this.noise = noise; } 

Do you do something like this in Typescript?

Constructor(name?:string, noise?:string){ if(name!= null) this.name =name; else this.name = ""; if(string != null) this.noise = noise; else this.noise = ""; } 

And so forth?

What about if you also have various primitives coming in say, you could declare an animal with an int or a string. Do you just use instanceof?

Thanks! Nathan

1 Answer 1

3

This can be done very simply:

class Animal { public name: string; public noise: string; constructor(name = 'default', noise = '') { this.name = name; this.noise = noise; } } 

This is also exactly equivalent to:

class Animal { constructor(public name = 'default', public noise = '') { } } 

Note that missing parameters in JavaScript have the value undefined, not null.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.