2017-04-04 94 views
3
function myFunc({ param1 }: {             
    param1: number;                
}) {                   
    // param1 is marked as mandatory in the definition, but we can bypass that 
}                    

const mismatchedFunc: ({}) => void = myFunc;         

mismatchedFunc({}); // No compile-time error 

我猜測,對於這種現象的原因,從打字稿的結構型性質莖函數調用使用結構類型和變量重新分配到旁路類型檢查,在{ param1: number }結構「適合「{}與「命名參數」

然而,這是不是不受歡迎的行爲(在這種情況下,或類的情況下),因爲它在很大程度上繞過了TypeScript提供的類型檢查?

這應該作爲一個錯誤提交嗎?

編輯1

由於@shusson指出,行爲(如V2.X)的預期(由於權衡),即使它是不可取的。

有關該問題根源的最相關討論,請參閱this GitHub issuefollow-up proposal以嘗試解決該問題。

回答

2

有兩件事情怎麼回事:

  1. structural typing

    爲打字稿的結構類型系統的基本規則是,x是其中y兼容如果y至少有相同的成員爲x。

  2. bivariant function parameters

    當比較類型的函數的參數,分配成功如果源參數是分配給所述目標參數,或者反之亦然

例如:

type t1 = { param1: number }; 
type t2 = { }; 

let f1 = (a: t1) => {}; 

let f2: (a: t2) => void = f1; // bivariant assignment 

let x: t1 = { param1: 1 }; 
let y: t2 = {}; 

y = x; // because of this, f1 is assignable to f2 through bivariant assignment 
x = y; // compile error 

f1(x); 
f1(y); // compile error 

f2(x); 
f2(y); 
+0

所以雙變量函數參數是一種不受歡迎的行爲,但這是一種預期並且是權衡的結果。那是對的嗎? – pleasedesktop

+0

是的,這是我的理解。 TypeScript有他們的文檔稱爲「不健全」的行爲,這是不可避免的,但仔細考慮。我認爲這些問題大部分都是由於TypeScript與JavaScript結合而引起的(在我看來這是一件好事)。 – shusson