I'm trying to integrate typescript into my learning path and understanding the differences with javascript.
So far I was able to resolve all issues but I got stuck on something that appears pretty basic.
function Person() {
// ERROR: this implicitly has type any because it does not have a type annotation
this.name = 'brad';
}
// ERROR: new expression, whose target lacks a construct signature, implicitly has an any type
const brad = new Person();
console.log( brad );
I tried some possible solutions:
- disabled no implicit this in tsconfig:
this would work in removing the first error, but the one on the
new Person()
remains - set this: any in the parameter parenthesis (with noimplicitthis to true)
function Person( this: any ) { // ERROR: unexpected any. specify a different type
- tried to use an arrow function to store it
- tried using constructor inside the Person function
Had a look at the official typescript handbook but I just don't seem to find anything that correlates with my current problem.
Why does the above code work in JS while in typescript I can't seem to make it work?
CodePudding user response:
Typescript is complaining here that it doesn't know at declaration what is the type of this
and what it should return
We can solve this in 2 ways -
Solution 1: (Preferred)
// Convert this constructor function to Person
class Person {
name = 'brad'
}
const brad = new Person();
console.log( brad );
Solution 2: (Hacky)
interface Person1 {
name: string
// All properties of Person goes here
}
const Person1 = function (this: Person1){
this.name = 'brad'
} as any as { new (): Person1 }
const foo = new Person1();
console.log(foo);