Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从typescript中继承的派生类重写静态变量_Typescript - Fatal编程技术网

如何从typescript中继承的派生类重写静态变量

如何从typescript中继承的派生类重写静态变量,typescript,Typescript,我希望静态方法的静态实现使用派生类的值。例如,在下面的简单示例中,当我调用User.findById()时,我希望它在执行基类SqlModel中定义的实现时使用重写的tableNameUser 如何确保基类static tableName使用“User”,这是本质上声明抽象静态属性的正确方法 class SqlModel { protected static tableName:string; protected _id:number; get id():number

我希望静态方法的静态实现使用派生类的值。例如,在下面的简单示例中,当我调用
User.findById()
时,我希望它在执行基类SqlModel中定义的实现时使用重写的tableName
User

如何确保基类static tableName使用“User”,这是本质上声明抽象静态属性的正确方法

class SqlModel {

    protected static tableName:string;

    protected _id:number;
    get id():number {
        return this._id;

    }

    constructor(){

    }

    public static findById(id:number) {
        return knex(tableName).where({id: id}).first();
    }

}

export class User extends SqlModel {

    static tableName = 'User';

    name:string;

    constructor(username){
        this.name = username;
    }
}
我会得到一个错误,说tablename没有定义,但是如果我说SqlModel.tablename,那么它就不使用派生类表名

User.findById(1); //should call the knex query with the tablename 'User'

您可以使用
此.tableName

class SqlModel {
    protected static tableName: string;

    public static outputTableName() {
        console.log(this.tableName);
    }
}

class User extends SqlModel {
    protected static tableName = 'User';
}

User.outputTableName(); // outputs "User"

我成功地获得了如下静态:

(<typeof SqlModel> this.constructor).tableName
(this.constructor).tableName

我相信在typescript>1.8中不起作用。存在解决方法:(this.constructor as any)。tableName如图所示:@Dominik区别在于,在本例中,问题是询问的是静态方法-
findById
-不是实例方法。问题是静态成员绑定到类,不能通过实例引用<代码>控制台.log(this.tableName)不起作用
console.log(SqlModel.tableName)
可以工作,但不是多态的
console.log((this.constructor as any).tableName)
可以工作并且是多态的,但并不美观。@snarf请注意这里的方法是
静态的
,而不是实例方法
this.constructor.tableName
在这种情况下在静态方法中是
未定义的
,而
this.tableName
可以工作。(编辑:可能我误解了,您是在回应上述评论?无论如何,使用
this.constructor.tableName
作为实例方法,使用
this.tableName
作为静态方法)我的错误。我读得不够仔细。我以为OP是从实例方法访问静态属性的。请注意,这是您在实例方法中要做的,而不是静态方法(问题是关于静态方法的,但无论如何,这是有用的信息)。