Typescript:new()未强制执行接口契约

ric*_*dpj 5 generics constructor interface typescript

我试图在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());
Run Code Online (Sandbox Code Playgroud)

编辑:更简单的形式:

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

表现出同样的错误.

bas*_*rat 2

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

interface INewable<T> {
    new(param: string): T;
}

function createInstance<T>(ctor: INewable<T>): T {
   return new ctor(1024); //why doesn't this fail?
}
Run Code Online (Sandbox Code Playgroud)

基本上我认为这是因为它是通用项目中的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?
}
Run Code Online (Sandbox Code Playgroud)

但以下情况确实如此:

interface INewable<T> {
    anything(): T;
}

function createInstance<T>(ctor: INewable<T>): T {
   return new ctor(1024); //fails
} 
Run Code Online (Sandbox Code Playgroud)

您可以在这里报告: https: //typescript.codeplex.com/workitem/list/basic,如果您这样做,我将不胜感激,以便我可以对该错误进行投票