如何在下面的代码中访问'y‘- attriubte?
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我不知道怎样才能解决这个问题。
发布于 2021-01-07 14:13:43
要么您知道将要返回的内容,然后返回精确的类型:
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);
}https://stackoverflow.com/questions/65613774
复制相似问题