[英]Property does not exist on type error when the property does exist
在制作以下 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!");
}
}
謝謝你的幫助!
如果它不是字符串或數組,則它是一個對象
if (Array.isArray(targeter)) {
// Array
} else if (typeof targeter === "string") {
// string
} else {
// Instance of targeterInterface
}
您可以使用稱為 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!"); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.