如何访问以下代码中的 'y' - 属性?
export type AutogeneratedResult = {
a: string
} | { a: string, b: string } | { y: string };
function foo(): AutogeneratedResult {
return {
y: 'test'
}
}
const x = foo();
console.log(x.y); // <---- Syntax error
我不知道如何解决这个问题。
答案 0 :(得分:0)
要么你确切地知道你要返回什么,然后你返回精确的类型:
type ChoiceA = { a: string };
type ChoiceB = { a: string, b: string };
type ChoiceC = { y: string };
export type AutogeneratedResult = ChoiceA | ChoiceB | ChoiceC;
function foo(): ChoiceC {
return {
y: 'test'
};
}
const x = foo();
console.log(x.y);
要么你必须检查返回类型:
type ChoiceA = { a: string };
type ChoiceB = { a: string, b: string };
type ChoiceC = { y: string };
export type AutogeneratedResult = ChoiceA | ChoiceB | ChoiceC;
function foo(): AutogeneratedResult {
return {
y: 'test'
};
}
const x = foo();
if ('y' in x) {
console.log(x.y);
}