通过打字稿中的 this.constructor 访问静态属性 [英] Access to static properties via this.constructor in typescript

查看:64
本文介绍了通过打字稿中的 this.constructor 访问静态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要写es6类:

class SomeClass {
    static prop = 123

    method() {
    }
}

如何在不显式使用 SomeClass 的情况下从 method() 访问静态 prop?在 es6 中,它可以使用 this.constructor 完成,但在 typescript this.constructor.prop 中会导致错误TS2339: Property 'prop' does not exist on type'函数'".

How to get access to static prop from method() without use SomeClass explicitly? In es6 it can be done with this.constructor, but in typescript this.constructor.prop causes error "TS2339: Property 'prop' does not exist on type 'Function'".

推荐答案

但在打字稿中 this.constructor.prop 会导致错误TS2339:属性 'prop' 在类型 'Function' 上不存在".

but in typescript this.constructor.prop causes error "TS2339: Property 'prop' does not exist on type 'Function'".

Typescript 不会将 constructor 的类型推断为 Function 之外的任何东西(毕竟……构造函数可能是一个子类).

Typescript does not infer the type of constructor to be anything beyond Function (after all ... the constructor might be a sub class).

所以使用断言:

class SomeClass {
    static prop = 123;
    method() {
        (this.constructor as typeof SomeClass).prop;
    }
}

更多关于断言

这篇关于通过打字稿中的 this.constructor 访问静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆