当用作构造函数调用与常规函数的一部分时,Typescript接口的行为会有所不同吗?

时间:2013-08-05 19:20:54

标签: typescript

为什么第一个例子编译但第二个例子生成“提供的参数与呼叫目标的任何签名都不匹配?”

interface Foo {
    s: string;
}

// example 1:
function abc(p: Foo[]) {    
}

// ok
abc([{s: ''}]);


// example 2:
class Blah {
    constructor(p: {stuff: Foo[]}) {
    }
}

// not ok: Supplied parameters do not match any signature of call target
var obj = new Blah({stuff: [{s: ''}]});

2 个答案:

答案 0 :(得分:2)

这是编译器中的一个错误。它已被修复;将要修复的下一个版本是0.9.1.0。

答案 1 :(得分:1)

我唯一要补充的是,如果你为stuff创建一个界面,它将起作用:

interface Foo {
    s: string;
}

interface Stuff {
    stuff: Foo[];
}

// example 1:
function abc(p: Foo[]) {    
}

// ok
abc([{s: ''}]);


// example 2:
class Blah {
    constructor(p: Stuff) {
    }
}

var obj = new Blah({stuff: [{s: ''}]});

See it in the TypeScript Playground