首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“或”-typed对象的访问属性

“或”-typed对象的访问属性
EN

Stack Overflow用户
提问于 2021-01-07 14:02:14
回答 1查看 22关注 0票数 1

如何在下面的代码中访问'y‘- attriubte?

代码语言:javascript
复制
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

我不知道怎样才能解决这个问题。

打字稿-游乐场:https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBDAnmYcCCBXGEDmwB2wUAhjMACYBKwAzhgDbwC8cA3gFBxzEBccNMKAEt8OdgF84AHzbc+A4aIA0cAEbzBInHEkzWcRBsXbxAbnbsAZhnwBjGEIj44liBAAUASj6ZseQiRkVLQM8BxcUMAwGFDO4VwGfADkZAJJnDoSFuy2TgJwIHAsrh6e5jl5EPTAAHT0uO4gNYhlQA

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-07 14:13:43

要么您知道将要返回的内容,然后返回精确的类型:

游乐场

代码语言:javascript
复制
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);

要么您必须检查返回类型:

游乐场

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65613774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档