【问题标题】:Union types : Property does not exist on type object联合类型:类型对象上不存在属性
【发布时间】:2020-09-27 15:15:02
【问题描述】:

在具有多种类型的接口属性上无法识别对象类型。 在我的例子中,answer 属性与 PostalAnswer 类型。

interface Question {
    id: number;
    answer: string | string[] | PostalAnswer;
}
interface PostalAnswer { address: string; city: string; code: string; }

const formQuestions: Question[] = [
    {
        id: 0,
        answer: 'Bonjour'
    },
    {
        id: 1,
        answer: { address: '1 rue', city: 'Paris', code: '75001' }
    }
];

console.log(formQuestions[1].answer.address);

typescript playground

我在最后一行收到此错误:

类型“字符串”上不存在属性“地址”|邮政回答 |细绳[]'。 类型“字符串”上不存在属性“地址”。 ts(2339)

注意:如果answer属性只有一种PostalAnswer,则不再报错。

【问题讨论】:

  • 如果您在 [typescript playground] 上发布一个显示您的类型错误的完整示例,您可能会获得更多帮助。

标签: typescript union-types


【解决方案1】:

您应该使用type guard

interface Question {
    id: number;
    answer: string | string[] | PostalAnswer;
}
interface PostalAnswer { address: string; city: string; code: string; }

const formQuestions: Question[] = [
    {
        id: 0,
        answer: 'Bonjour'
    },
    {
        id: 1,
        answer: { address: '1 rue', city: 'Paris', code: '75001' }
    }
];

const question = formQuestions[1];
if (typeof question.answer === "object" && !Array.isArray(question.answer)) { // Typeguard
    console.log(question.answer.address);
}

你也可以做一个函数:

console.log(isPostalAnswer(formQuestions[1].answer) && formQuestions[1].answer.address);

function isPostalAnswer(potentialAnswer: any): potentialAnswer is PostalAnswer {
    return typeof potentialAnswer === "object"
        && "address" in potentialAnswer
        && "city" in potentialAnswer
        && "code" in potentialAnswer;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 2019-10-11
    • 2018-02-10
    • 2018-03-03
    • 1970-01-01
    相关资源
    最近更新 更多