typescript - 属性 'runStaticMethod' 是 'DemoClass' 类型的静态成员

标签 typescript static

构建以下 typescript 代码时出现以下错误。

Property 'runStaticMethod' is a static member of type 'DemoClass'

typescript 代码:


export class Main {
    constructor(private demo: DemoClass) { }
    public run() {
        this.demo.runStaticMethod();
    }
}

export class DemoClass {
    public static runStaticMethod() {
        console.log('run...');
    }
}

new Main(DemoClass).run();


我收到以下信息 console构建上述内容时出错 typescript代码。但是javascript代码按预期运行。

控制台错误:
Chitty:tsc NatarajanG$ tsc
src/index.ts:5:19 - error TS2576: Property 'runStaticMethod' is a static member of type 'DemoClass'

5         this.demo.runStaticMethod();
                    ~~~~~~~~~~~~~~~

Chitty:tsc NatarajanG$ 

最佳答案

因为它是一个静态属性,您应该按照 TS 要求的方式访问它:DemoClass.runStaticMethod() , 尽管 javascript 支持 this.demo.runStaticMethod() .

https://www.typescriptlang.org/docs/handbook/classes.html#static-properties

Each instance accesses this value through prepending the name of the class. Similarly to prepending this. in front of instance accesses, here we prepend Grid. in front of static accesses.

关于typescript - 属性 'runStaticMethod' 是 'DemoClass' 类型的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55262583/

相关文章:

angular - 直接从http(observable)服务(函数)返回结果,而不返回Observable

angular - 以 Angular 拆分和显示字符串值

带有一般错误的 typescript 缩小类型

javascript - 尽管 MFP 服务器已关闭,但仍返回访问 token

c++ - 如何每n次重置一个函数变量?

C++ 通过跨多个 .cpp 文件所需的信息一次性读取一个头文件

php - 半静态/动态页面

javascript - 在 TypeScript 中使用 interfect 定义对象数组?

java - 关于Java中的静态final关键字

class - 使用 Powershell 访问静态类中的静态类