首页 文章

在Typescript中有“类”类型吗?并且“任何”包含它吗?

提问于
浏览
15

在Java中,您可以使用"Class"类型将class to a method作为参数 . 我没有在打字稿文档中找到任何类似的东西 - 是否可以将类交给方法?如果是这样,"any"类型是否包含此类类型?

背景:我遇到了Webstorm的问题,告诉我我无法将一个类交给Angular 2中的 @ViewChild(...) . 然而,Typescript编译器并没有抱怨 . @ViewChild() 的签名似乎是 "Type<any> | Function | string" ,所以我想知道是否有任何包括类 .

5 回答

  • 1

    您在打字稿中所要求的等价物是 { new(): Class } 类型,例如:

    class A {}
    
    function create(ctor: { new(): A }): A {
        return new ctor();
    }
    
    let a = create(A); // a is instanceof A
    

    code in playground

  • 6

    是否可以将类交给方法?如果是这样,“any”类型是否包含此类类型?

    是的,是的 . any 包括每种类型 .

    以下是仅包含类的类型示例:

    type Class = { new(...args: any[]): any; };
    

    然后使用它:

    function myFunction(myClassParam: Class) {
    }
    
    class MyClass {}
    
    myFunction(MyClass); // ok
    myFunction({}); // error
    

    你不应该在 Function 的类中传递错误,因为它应该可以正常工作:

    var func: Function = MyClass; // ok
    
  • 5

    Angular内部declare Type as:

    export interface Type<T> extends Function { new (...args: any[]): T; }
    

    使用TypeScript3,应该可以在没有函数重载的情况下添加types for arguments

    export interface TypeWithArgs<T, A extends any[]> extends Function { new(...args: A): T; }
    

    例:

    class A {}
    
    function create(ctor: Type<A>): A {
        return new ctor();
    }
    
    let a = create(A);
    
  • -2

    这应该工作 - delcare a type Type

    // just two different classes
    class MyClass {}
    class OtherClass {
        constructor(protected IsVisible: boolean) {}
    }
    
    // here we declare our type named "Type"
    type Type = Function;
    
    // we will consume just params of a Type (classes)
    function take(type: Type){  
    }
    
    
    // build will fail
    take(1);          // not a Type
    take("A")         // not a Type
    take(new Date()); // not a Type
    
    // will be working
    take(MyClass);    // this is a type
    take(OtherClass); // this is a type
    

    a working example

    或者类似于界面

    // just two different classes
    class MyClass {}
    class OtherClass {
        constructor(protected IsVisible: boolean) {}
    }
    
    // here we declare our type named "Type"
    interface Type extends Function {}
    
    // we will consume just params of a Type (classes)
    function take(type: Type){  
    }
    
    
    // build will fail
    take(1);          // not a Type
    take("A")         // not a Type
    take(new Date()); // not a Type
    
    // will be working
    take(MyClass);    // this is a type
    take(OtherClass); // this is a type
    

    示例here

  • 19

    Java和JavaScript中的继承模型是不同的 . 在Java中,您在类的所有实例之间共享一个Class对象 . JavaScript使用原型继承,而不存在Class对象 .

    TypeScript和ES6都只使用class关键字作为语法糖而不更改可执行代码的继承模型 .

相关问题