typescriptdecoratortsctypescript-decoratortypescript-class

Property 'id' does not exist on type 'Person' when using decorator


I know this seems duplicated but I haven't found a solution to this specific problem (with decorator) I'm using the DefaultParameterValue to add a default parameter to a class:

function DefaultParameterValue<T extends { new(...args: any[]): {} }>(constructor: T) {
    return class extends constructor {
        id: number = 123;
    }
}

@DefaultParameterValue
class Person{
    name
    constructor(name: string) {
        this.name = name
    }
}
const sam = new Person("Sam")
console.log(sam.id)

This is giving me an error:

Property 'id' does not exist on type 'Person'.

I don't know if this makes a difference, but I'm my tsconfig.json is like this:

{
  "compilerOptions": {
    "target": "ES5",   
    "experimentalDecorators": true,                   
    "module": "commonjs",                               
    "rootDir": "./src", 
    "skipLibCheck": true                                
  }
}

How can I remove the error?


Solution

  • Hope this helps but it looks like its a matter of declaring the type expected for same

     const sam: Record<string, any> = new Person("Sam");
     console.log(same.id);
    

    folow this link and click run and it should work example: https://www.typescriptlang.org/play?declaration=false&experimentalDecorators=true&target=1&module=1#code/GYVwdgxgLglg9mABAEQKbAIYgDZQAoYBOGAtqlKoQGobYioA8AKoqgB4VgAmAzogN6IwqAO4AKAHRSiAcx4AuRBjABPANoBdAJSL+AX0R6AfGIgIeUQiGhxCiploEAoRK8SFyIQkgjYMPPnZOXkQzMAsrG0JnN1jEGC5FMBASACNKRABeRABGACYAZgBuFzc9J3KnAAE0TBx8IlJySho6VCdffz48Sh4EflLXMCbB0PNLayhbMWGyRQiYMBlHAbi3KAALGB4JWdQsoRHY8vKwi0QeUkUAJVQzQi4GBaWAGiVVIwPhEUQewj6wGIAEQAZVIQK0HXMcGwqAk2DgMjElxIEgSkNcQA