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

时间:2020-02-05 15:17:23

标签: typescript typescript-typings

以下抽象的TS场景:

[Example] Attena Illusive - 01 [720p].mkv

在控制台记录 SELECT ts_rank_cd(to_tsvector('english', name), query, 1) as rank, * FROM tables, plainto_tsquery('Attena Illusive 1') query WHERE to_tsvector('english', name) @@ query ORDER BY rank desc 时引发TypeScript错误,因为它显然不存在。

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,也很可能存在。

为什么会这样?

2 个答案:

答案 0 :(得分:2)

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

您可以使用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:");
};

如果您首先没有属性okay,就不会幸福。

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

Here is a playground

答案 1 :(得分:0)

您可以使用Typescript type assertion(类似于其他语言的投射)。

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