Typescript:组合类型上不存在属性?

标签 typescript typescript-typings

以下抽象的 TS 场景:

interface EmotionsOkay {
  emotion: string;
  okay: "yap";
}
interface EmotionsNotOkay {
  emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
  console.log(test.okay ? "happy :D" : "sad D:");
};

在控制台记录 test.okay 时抛出 TypeScript 错误,因为它显然不存在。

Property `okay` does not exist on type `UndetereminedEmotion`.

即使它很可能存在,但如果传递给该方法的测试是 EmotionsOkay 类型。

为什么会发生这种情况?

最佳答案

此时,TS 不知道它是什么类型,它可能是 EmotionsOkay 并且一切都会好起来的,或者它可能是 EmotionsNotOkay 并且属性 好吧不会存在。这就是您收到此错误的原因。您需要验证它是什么类型。

您可以使用 in 关键字来验证这一点,

interface EmotionsOkay {
  emotion: string;
  okay: "yap";
}
interface EmotionsNotOkay {
  emotion: string;
}
type UndetereminedEmotion = EmotionsOkay | EmotionsNotOkay;
const areYouOkay = (test: UndetereminedEmotion) => {
  console.log('okay' in test && test.okay ? "happy :D" : "sad D:");
};

如果您一开始就没有属性(property)好吧,您就不会快乐。

如果您想知道为什么在这种情况下不能使用 instanceof,请查看 this question

Here is a playground

关于Typescript:组合类型上不存在属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60078892/

相关文章:

visual-studio - Typescript编辑并继续visual studio 2015

typescript - 有没有办法实现 <T>(x : Promise<AsyncIterableIterator<T>>): AsyncIterableIterator<T> in TypeScript?

typescript - Keyof 推断字符串 |键只是字符串时的数字

typescript - 扩展 typescript 变量声明

typescript - Bootstrap4 types(index.d.ts) 在使用 TypeScript 3.9 和 Libman 的 Visual Studio 2019 上找不到模块 'popper.js'

javascript - 设置接口(interface)方法时,在 VSCode 中出现智能感知错误

angularjs - 如何排除 `node_modules/@types/**/node_modules` ?

javascript - Typescript Konva 类变量不在范围内

javascript - 使用 typescript ENUM 动态传递 props

typescript - 使 typescript 函数返回类型以输入为条件