打字稿:带有instanceof的条件类型检查无法按预期工作

时间:2018-12-19 17:36:25

标签: typescript

export const initPeer = (t: Chat | Diagnostic, test?: boolean) => {

  // bleep bloop ... code here

  if (test && t instanceof Diagnostic) {
    setupPeerTest(t, p);
  } else if (t instanceof Chat) {
    setupPeer(t, p);
  }
};

这段代码给了我TSError。我以为我已经强迫他们成为一种或另一种...

src/components/Chat/peer.ts:139:19 - error TS2345: Argument of type 'Chat | Diagnostic' is not assignable to parameter of type 'Diagnostic'.
  Type 'Chat' is missing the following properties from type 'Diagnostic': defaultState, browsers, append, isPassed

139     setupPeerTest(t, p);
                      ~

src/components/Chat/peer.ts:141:15 - error TS2345: Argument of type 'Chat | Diagnostic' is not assignable to parameter of type 'Chat'.
  Type 'Diagnostic' is missing the following properties from type 'Chat': tickTimer, tabDiv, adapter, default, and 28 more.

141     setupPeer(t, p);
                  ~

1 个答案:

答案 0 :(得分:2)

  

我会以为我已经强迫他们成为一种或另一种...

我认为TypeScript不会在这种程度上评估您的逻辑。我认为您将需要类型断言:

if (test && t instanceof Diagnostic) {
  setupPeerTest(<Diagnostic>t, p);
// -------------^^^^^^^^^^^^
} else if (t instanceof Chat) {
  setupPeer(<Chat>t, p);
// ---------^^^^^^
}

if (test && t instanceof Diagnostic) {
  setupPeerTest(t as Diagnostic, p);
// --------------^^^^^^^^^^^^^^
} else if (t instanceof Chat) {
  setupPeer(t as Chat, p);
// ----------^^^^^^^^
}

也许在那里没有test变量,它也许可以推断出来,但是...