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'
constinstead oflet. But without a reproducible example it's hard to know for sure if that will work for your use case.