【问题标题】:Class like a type in interface of Typescript像 Typescript 接口中的类型一样的类
【发布时间】:2017-11-16 12:09:06
【问题描述】:

是否可以像接口中的类型一样使用 Class ?例如,我有一个类 Animal,我可以使用类似的东西:

interface I {
    object: Animal
}

我在这种情况下遇到了错误:

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:类型“A”上不存在属性“foo”

【问题讨论】:

    标签: class typescript types interface


    【解决方案1】:

    你需要使用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!'));
        }
    }
    

    【讨论】:

      【解决方案2】:

      您的代码中的问题是 foo 方法是静态的。静态只能用于类而不是对象。

      在你的情况下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-28
        • 2020-04-17
        • 1970-01-01
        • 2019-06-27
        • 2019-04-27
        • 1970-01-01
        • 2020-05-04
        相关资源
        最近更新 更多