假設我有一個帶有多個可選引數的函式。
為什么通過arguments關鍵字沒有基于函式數量的型別保護,以及如何在不改變實作和不丑陋的強制轉換的情況下解決這個問題?
function test(arg0?: string, arg1?: string, arg2?: string) {
if (arguments.length === 1) {
// I expect arg0 to be of type string instead of string | undefined
}
if (arguments.length === 2) {
// I expect arg0 and arg1 to be of type string instead of string | undefined
}
if (arguments.length === 3) {
// I expect arg0, arg1 and arg2 to be of type string instead of string | undefined
}
}
uj5u.com熱心網友回復:
請看arguments型別:
interface IArguments {
[index: number]: any;
length: number;
callee: Function;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
您可能已經注意到,關鍵字arguments對引數型別的數量一無所知。從打字稿的角度來看,它甚至不受函式背景關系的約束。它只是一個具有一堆與函式引數無關的屬性的物件。
此外,length財產不像打字員那樣起作用。您無法[string, string]僅通過檢查 if來推斷例如型別length === 2。請看這個答案。您會找到指向 github 問題和此hasLengthAtLeast幫助程式的適當鏈接。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366070.html
標籤:打字稿
上一篇:如何表示不可變物件的不可變陣列?
