当属性存在时,出现类型错误时该属性不存在



我在编写以下TypeScript代码时收到了上述错误。问题显然是url、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
}

你可以使用TypeScript中一个叫做type-guard函数的特性来检查参数的类型。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!");
}
}

相关内容

  • 没有找到相关文章

最新更新