我知道以下并不意味著回傳的“型別”是無效的。我的理解是 voidFunc 什么都不回傳,因為它回傳“void”。為什么它回傳任何型別?
type voidFunc = () => void
const myFunc: voidFunc = () => {
return 'hello'
}
和下面這樣寫有什么不同?
type voidFunc = () => any
uj5u.com熱心網友回復:
請參閱功能的可分配性
回傳型別無效
函式的 void 回傳型別可能會產生一些不尋常但預期的行為。
具有回傳型別的背景關系型別不會強制函式不void回傳某些內容。另一種說法是具有回傳型別 ( ) 的背景關系函式型別,當實作時,可以回傳任何其他值,但將被忽略。voidtype vf = () => void
因此,該型別的以下實作() => void是有效的:
type voidFunc = () => void;
const f1: voidFunc = () => {
return true;
};
const f2: voidFunc = () => true;
const f3: voidFunc = function () {
return true;
};
并且當其中一個函式的回傳值被賦值給另一個變數時,它會保留 void 的型別:
const v1 = f1();
const v2 = f2();
const v3 = f3();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450781.html
上一篇:在R中使用熱圖重新排序x軸
