【问题标题】:Typescript: new() Interface contract not enforced打字稿:新()接口合同未强制执行
【发布时间】:2013-09-01 17:59:04
【问题描述】:

我正在尝试在 Typescriptlang.org 的操场上测试一个相当做作的示例。我的 INewable 接口指定了一个字符串构造函数参数。在我的工厂方法的主体中,我不遵守此约束(通过使用数字或使用 void 参数列表调用)。我没有收到错误或警告。

是我做错了什么还是这是一个错误?

interface INewable<T> {

    new(param: string): T;
}

interface IToStringable {

    toString(): string;
}

module Factory {

    export function createInstance<T extends IToStringable>(ctor: INewable<T>): T {

        return new ctor(1024); //why doesn't this fail?
    }
}

var d = Factory.createInstance(Function);

alert(d.toString());

编辑:更简单的形式:

function createInstance<T>(ctor:new(s:string)=>T):T {
    return new ctor(42); //why doesn't this fail either
}

表现出同样的错误。

【问题讨论】:

    标签: generics interface constructor typescript


    【解决方案1】:

    不错的收获。它是编译器中的一个错误。更简单的示例:

    interface INewable<T> {
        new(param: string): T;
    }
    
    function createInstance<T>(ctor: INewable<T>): T {
       return new ctor(1024); //why doesn't this fail?
    }
    

    基本上我认为这是因为T 在通用项目中属于any 类型。这让编译器感到困惑,它的一部分(不完全)认为ctor 也是any

    例如以下不是错误:

    interface INewable<T> {
        new(param: string,anotherparam): T;
    }
    
    function createInstance<T>(ctor: INewable<T>): T {
       return new ctor(1024); //why doesn't this fail?
    }
    

    但以下是:

    interface INewable<T> {
        anything(): T;
    }
    
    function createInstance<T>(ctor: INewable<T>): T {
       return new ctor(1024); //fails
    } 
    

    你可以在这里报告它:https://typescript.codeplex.com/workitem/list/basic,如果你这样做,我会很感激一个链接,以便我可以对错误进行投票

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2017-09-29
      • 2021-12-03
      • 2020-05-31
      • 2017-09-02
      • 1970-01-01
      • 2019-06-19
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多