访问“或”类型对象的属性

时间:2021-01-07 14:02:14

标签: typescript

如何访问以下代码中的 '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

我不知道如何解决这个问题。

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

1 个答案:

答案 0 :(得分:0)

要么你确切地知道你要返回什么,然后你返回精确的类型:

playground

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);

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

playground

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);
}
相关问题