程式碼
function t(a:number,b:number){
return a+b
}
console.log(t(3,5));
console.log(t(3,'5'));
如果經過tsc的話,其實沒有任何變化
還是
function t(a:number,b:number){
return a+b
}
console.log(t(3,5));
console.log(t(3,'5'));
但是 tsc 會警告
test_2.ts:6:17 - error TS2345: Argument of type '"5"' is not assignable to parameter of type 'number'.
'number'
如果我想要在經過 tsc 後保留型別檢查(像類似下面這樣)
function t(a, b) {
if typeof(a) != typeof(0)
throw (new Error('type is not number'))
return a + b;
}
console.log(t(3, 5));
console.log(t(3, '5'));
請問如何做到呢?