Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
wjhguitarman Avatar asked Oct 21 '25 16:10

wjhguitarman


2 Answers

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.

like image 195
Ryan Cavanaugh Avatar answered Oct 23 '25 08:10

Ryan Cavanaugh


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
like image 30
Alex Dresko Avatar answered Oct 23 '25 06:10

Alex Dresko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!