#Typescripting a method separated from an object

1 messages · Page 1 of 1 (latest)

marsh fog
#

Hi how do I go about resolving the TS errors in below code?
I've bolded with ****** the ones that throw errors and complaining that they have implicitly any type

  function Pet(type: any, legs: any) {
    **this**.type = type;
    **this**.legs = legs;
  
    **this**.logInfo = function() {
      console.log(this === myCat); // => true
      console.log(`The ${this.type} has ${this.legs} legs`);
    };
  }
  
  const myCat = **new Pet('Cat', 4)**;
  
  // Create a bound function
  const boundLogInfo = myCat.logInfo.bind(myCat);
  // logs "The Cat has 4 legs"
  setTimeout(boundLogInfo, 1000);
late onyx
#

you can't put formatting inside a codeblock (except md, kinda) fyi

#

anyways you haven't told ts that Pet is a constructor function

#

im not sure you can

#

why not just use a class?

marsh fog
#

Interesting, so some format may no longer work when translating to TS

#

I'm still kinda noob in JS so not sure how to turn it into a class

#

or vice versa

marsh fog
#

I think I managed to convert it to a class but it still complains in several areas.

  class Pet {
    constructor(type: any, legs: any){
        this.type = type;
        this.legs = legs;
    }

    this.logInfo = function() {
        console.log(this === myCat); // => true
        console.log(`The ${this.type} has ${this.legs} legs`);
    };
  }
junior comet
#

Constructor functions are the old old way of doing classes back when JS didn't have dedicated class syntax, it shouldn't be used nowadays.

#

Based on best guesses, you probably want something like:

class Pet {
    type: string
    legs: number

    constructor(type: string, legs: number) {
        this.type = type
        this.legs = legs
    }

    logInfo() {
        console.log(...)
    }
}
#

There's also a shorthand for doing constructors + parameters + properties:

class Pet {
    constructor(
        public type: string,
        public legs: number,
    ) {}
}

Although I personally don't like it.

marsh fog
#

Yea I prefer more straightforward syntax like your first one

#

Thank you Chris and Burrito