简体   繁体   中英

TypeScript: Property 'propertyName' does not exist on type 'Function'

TypeScript compiler is giving me an error on the following code example although the generated JavaScript on https://www.typescriptlang.org/play/ works as intended

The error is: error TS2339: Property 'tableName' does not exist on type 'Function'.

class ActiveRecord {
    static tableName(): string { // override this
        return "active_record";
    }

    static findOne(): any {
        return 'Finding a record on table: ' + this.tableName();
    }

    save(): void {
        console.log('Saving record to table: ' + this.constructor.tableName());
    }
}

class MyModel extends ActiveRecord {
    static tableName(): string {
        return "my_model";
    }
}

let x = new MyModel();
x.save(); // "Saving record on table: my_model"
console.log(MyModel.findOne()); // "Finding a record on table: my_model"

Is there is anything I can do to fix this error?

Replace this

this.constructor.tableName()

With this

ActiveRecord.tableName()

As a static function is must be called using the class namespace.

To fix the TypeScript error and still get the intended behavior (not using ActiveRecord.tableName()) you can cast the constructor to a typeof ActiveRecord

(this.constructor as typeof ActiveRecord).tableName())

Reference link: Access to static properties via this.constructor in typescript

One way would be to NOT use the static keyword on your properties. Otherwise use ActiveRecord.tableName()

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