简体   繁体   English

类像Typescript接口中的类型

[英]Class like a type in interface of Typescript

Is it possible to use Class like a type in interface ? 是否可以在接口中像使用类型一样使用Class? For example, I have a class Animal, can I use something like: 例如,我有一个动物类,我可以使用类似的东西:

interface I {
    object: Animal
}

I've got en error on this situation: 在这种情况下,我遇到了错误:

class A {
     public static foo(text: string): string {
         return text;
     }
  }

interface IA {
  testProp: A;
  otherProp: any;
}

class B {
    constructor(prop: IA) {
        console.log(prop.otherProp);
        console.log(prop.testProp.foo('hello!'));
    }
}

TS2339: Property 'foo' does not exist on type 'A' TS2339:类型“ A”上不存在属性“ foo”

You need to use typeof A : 您需要使用typeof A

class A {
    public static foo(text: string): string {
        return text;
    }
}

interface IA {
  testProp: typeof A;
  otherProp: any;
}

class B {
    constructor(prop: IA) {
        console.log(prop.otherProp);
        console.log(prop.testProp.foo('hello!'));
    }
}

The problem in your code is that the foo method is static. 您的代码中的问题是foo方法是静态的。 Static can only be used on classes not object. 静态只能用于没有对象的类。

In your case: 在您的情况下:

A.foo("hello); //works
new A().foo("hello"); //doesn't work since it's an instance of A

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM