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

this code gives me the TSError. I would have thought that I already forced them to be of one type or another...

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);
                  ~
4
  • I wonder if it's something else before all this, and then this is a side-effect? Because I can't replicate it in the TypeScript playground. Can you update your question w/an MCVE? Commented Dec 19, 2018 at 17:46
  • what version of TS are you on? instanceof should act as a typeguard Commented Dec 19, 2018 at 18:11
  • Please post your definitions for your classes. Might have something to do with this though it's a bit different... Commented Dec 19, 2018 at 18:18
  • they do have a very similar structure so I think that link is the problem. I will post a full example if I can get some time Commented Dec 20, 2018 at 2:12

1 Answer 1

2

I would have thought that I already forced them to be of one type or another...

I don't think TypeScript evaluates your logic to that degree. I think you'll need type assertions:

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

Or

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

Perhaps without the test variable in there it might be able to infer it, but...

Sign up to request clarification or add additional context in comments.

2 Comments

it works, the weird part though is that the compiler never gave me errors until just now so it must have been something that changed in a more recent update of typescript?
...except I can't replicate that in the PlayGround (including with the flag), so this may be incorrect. If I set up your situation, I don't get an error from TS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.