如果我定義這樣的型別:type Name = string | Regex并將其傳遞給函式,那么TypeScript發現傳遞了哪種型別的方法是什么?
很容易找到 JavaScript 的答案,但我正在為 TypeScript 苦苦掙扎。也許那是因為答案是相同的,但我希望有一種編譯時的檢查方式。
uj5u.com熱心網友回復:
Typescript 沒有任何特殊的方法來縮小型別的范圍。您需要使用常規 javascript 來縮小型別,如果您使用 typescript 會推斷出內部if陳述句(和其他控制陳述句),型別只能是一種可能的型別。
因此,要檢查某物是否是您可以使用的字串typeof foo === "string",并檢查您可以檢查的正則運算式foo instanceof RegExp。
type Name = string | RegExp;
const test: Name = Math.random() > 0.5 ? 'hi' : /ab c/;
if (typeof test === 'string') {
console.log(test.toUpperCase());
}
if (test instanceof RegExp) {
console.log(test.flags);
}
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409681.html
標籤:
上一篇:型別'IntrinsicAttributes&{name:string;上不存在屬性'item'href:字串;}'
下一篇:打字稿修改或擴展呼叫簽名
