简体   繁体   中英

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 ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM