联合类型:类型对象上不存在属性

时间:2020-06-08 15:35:31

标签: typescript union-types

在具有多种类型的接口属性上无法识别对象类型。 就我而言,类型为answer的{​​{1}}属性。

PostalAnswer

typescript playground

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

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

注意::如果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); 属性只有一种类型answer,就不会再有错误了。

1 个答案:

答案 0 :(得分:2)

您应该使用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;
}