wjhguitarman
wjhguitarman

Reputation: 1073

Access properties of a class in Typescript

Say I have a class in Typescript.

class MyAnimal {

   constructor(param1, param2) {
       voice: param1;
       height: param2;
   }
}

How do I actually construct the class so that I can access those properties when using the object:

var gorilla = new MyAnimal(param1, param2);

The above yields a compile error: Error TS2094: "The property voice does not exist on value of type 'MyAnimal'."

I converted this over from javascript, where it was working fine, however then it looked like this:

var MyAnimal = function (param1, param2) {
    return {
        voice: param1,
        height: param2,
    }
}

With that, I could access properties all day

var gorilla = MyAnimal(param1, param2);
if (gorilla.height < 5)
    alert("It's a baby gorilla!");

I am pretty new to Typescript/javascript, so there's a lot I am still trying to figure out. I wouldn't think it should be that hard to access properties. I have a suspicion I am just trying to access it incorrectly.

Am I just building the class wrong? Why can't I retrieve properties when I new up an instance of MyAnimal?

Upvotes: 4

Views: 8180

Answers (2)

Alex Dresko
Alex Dresko

Reputation: 5213

This might be the easiest way to fix your code. This automatically creates the public property from the constructor parameters.

class MyAnimal {
       constructor(public voice, public height) {
   }
}

So now you can do this:

var animal = new MyAnimal("rawr", 23);

// use animal.voice

Upvotes: 2

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221342

constructor(param1, param2) {
   voice: param1;
   height: param2;
}

This code simply defines two statement labels called 'voice' and 'height' and does nothing with the parameters. Instead what you want to do is:

class MyAnimal {
    voice: string;
    height: number;

   constructor(param1, param2) {
       this.voice = param1;
       this.height = param2;
   }
}

You might want to read the TypeScript Tutorials to get a feel for the basics of the language.

Upvotes: 3

Related Questions