简体   繁体   English

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

[英]Property does not exist on type error when the property does exist

I've received the aforementioned error when making the following TypeScript code.在制作以下 TypeScript 代码时,我收到了上述错误。 The problem is obviously that the urls, type and sub properties don't exist on a parameter of the string[] type, but they would not be read if that was the type of the targeted parameter.问题显然是 urls、type 和 sub 属性不存在于 string[] 类型的参数上,但如果这是目标参数的类型,它们将不会被读取。 I'm extremely new to TypeScript, this is my first attempt working with it, so I'm probably missing something relatively basic.我对 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!");
    }
}

Thanks for any help!谢谢你的帮助!

If it is not a string or an array , otherwise it is an object如果它不是字符串数组,则它是一个对象

if (Array.isArray(targeter)) {
    // Array
} else if (typeof targeter === "string") {
    // string
} else {
    // Instance of targeterInterface
}

You can use a TypeScript feature called type-guard function to check what is the type of the argument.您可以使用称为 type-guard 函数的 TypeScript 功能来检查参数的类型。 https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM