在制作以下 TypeScript 代碼時,我收到了上述錯誤。問題顯然是 urls、type 和 sub 屬性不存在于 string[] 型別的引數上,但如果這是目標引數的型別,它們將不會被讀取。我對 TypeScript 非常陌生,這是我第一次嘗試使用它,所以我可能缺少一些相對基本的東西。
interface targeterInterface {
urls: string | string[];
type?: string;
sub?: string;
}
function exp(targeter: string | targeterInterface | string[]) {
let target: string[] | string;
let type: string;
let sub: string;
if (typeof targeter === "object") {
target = targeter.urls;
type = targeter.type;
sub = targeter.sub;
} else if (typeof targeter === "string") {
target = targeter;
} else {
console.log("It's an array!");
}
}
謝謝你的幫助!
uj5u.com熱心網友回復:
如果它不是字串或陣列,則它是一個物件
if (Array.isArray(targeter)) {
// Array
} else if (typeof targeter === "string") {
// string
} else {
// Instance of targeterInterface
}
uj5u.com熱心網友回復:
您可以使用稱為 type-guard 函式的 TypeScript 功能來檢查引數的型別。 https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
interface targeterInterface {
urls: string | string[];
type: string; // had to change since, the type in the function is not optional
sub: string; // had to change since, the sub in the function is not optional
}
function isTargeterInterface(item: unknown): item is targeterInterface {
return (item as targeterInterface).type !== undefined;
} // this is a type guard function
function exp(targeter: string | targeterInterface | string[]) {
let target: string[] | string;
let type: string;
let sub: string;
if (isTargeterInterface(targeter)) { // calling a function to check if it implements interface provided above
target = targeter.urls;
type = targeter.type;
sub = targeter.sub;
} else if (typeof targeter === "string") {
target = targeter;
} else {
console.log("It's an array!");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330859.html
標籤:javascript 打字稿
