2016-01-12 14 views
2

我是新来的打字稿,我发现一些意想不到的关于协变性/反差异行为。协方差/对比方差中的意外行为像打字稿的分配

这里的代码片段:

interface Func1 { 
    (): { prop1: string } 
} 

// assignment similar to covariance 
var f1: Func1 = function() { return { prop1: "", prop2: 0 }; } 

interface Func2 { 
    ({prop1: string, prop2: number}): void; 
} 

// assignment similar to contra-variance 
var f3: Func3 = function (a: { prop1: string }) { } 

interface Func3 { 
    ({prop1: string}): void; 
} 

// assignment violates principle of contra-variance. 
// expect a compiling error but there isn't. 
var f3: Func3 = function (a: { prop1: string, prop2: number }) { alert(a.prop2); } 

// here occurs a non-existing field accessing 
// it might be unexpected and was possible to be eliminated by static checking on assignment to 'f3'. 
f3({ prop1: "" }); 

分配给F1是确定的,因为匿名函数的返回值可以被分配给FUNC1返回值类型。

分配到f2是确定太因为馈送到FUNC2类型参数可以被分配给参数“A”的匿名函数。

分配F3要失败,因为送入FUNC3类型参数不能分配给说法“一”匿名函数,所以我期望编译引发错误,但实际上并非如此。

当调用f3时,这会导致意外的访问冲突。

我的问题是,是预期的行为,或者它打字稿设计/实施的缺陷?

回答