2

Can someone please explain why the first example works in Typescript, but the second example throws an error??? Here is a live example in a Typescript playground.

const {type, payload} = action;

switch(type) {

...

  //*** EXAMPLE 1 ***//

  case "CREATE_VARIABLE":
    if (payload == null || typeof payload === "string" || !("color" in payload)) return state;
    return createVariable(state, payload);

...


  //*** EXAMPLE 2 (Throws error in Typescript) ***//

  case "CREATE_VARIABLE":
    const isNotAVariable = (payload == null || typeof payload === "string" || !("color" in payload));
    if(isNotAVariable) return state;

    return createVariable(state, payload);

...

}

The second example throws the following Typescript error:

Argument of type 'string | Formula | Variable | Constant | undefined' is not assignable to parameter of type 'Variable | undefined'.
  Type 'string' is not assignable to type 'Variable | undefined'
6
  • 4
    If you can make this code into a minimal reproducible example suitable for dropping into a standalone IDE like The TypeScript Playground (<-- that's a link to your code) then someone can answer with testable code more quickly. You're probably looking for a feature that will be released in TS4.4, although you'll need const instead of let. But without a reproducible example it's hard to know for sure if that will work for your use case. Commented Aug 25, 2021 at 16:37
  • We dont have enough information to answer this for you, we need more context Commented Aug 25, 2021 at 16:53
  • I have now added a live example with the full context showing the error in a Typescript playground. Commented Aug 25, 2021 at 16:57
  • 2
    The link posted by jcalz explains the issue—TS does not currently do deep control flow analysis; the referenced version will enhance it. Commented Aug 25, 2021 at 17:28
  • 2
    As mentioned above, your example code will work when TS4.4 is released, see this. Commented Aug 26, 2021 at 14:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.