EN VI

Inconsistent TypeScript Type Inference in Conditional Statement?

2024-03-13 03:30:08
How to Inconsistent TypeScript Type Inference in Conditional Statement?

My goal is to avoid repeating many times in switch cases of such checks of the existence of the id or value

Error Message:

The argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.ts(2345)

Code DEMO

Code snippet:

export const enum Message {
    setItem = 'setItem',
}

function foo(message: Message, data: Partial<Record<string, string>>) {
    const isValid = data.id != null && data.value != null;

    switch (message) {
        case Message.setItem: {
            if (isValid) {
                setItem(data.id, data.value);
            }
        }
    }
}

const setItem = (id: string, value: string | object) => {
    return id + value;
}

I'm getting a type error within setItem(data.id, data.value);

Additional Information:

  1. storage.setItem() expects the first argument to be a string.
  2. The error seems to suggest that TypeScript is not able to infer that event.data.data.id is always a string, even though isValid should ensure this.
  3. In practice I have many of these switch cases in some of them I need to check id in others I don't

Solution:

you can make type promotion functions in typescript: more info

function isValid(element: Partial<Record<string, string>>): 
element is Partial<Record<string, string>> & {id: string, value: string}
{
    return element.id != null && element.value != null;
} 

and you can use this in an if statement to promote your type.

if(isValid(data)){
    const id: string = t.id; //typescript will not complain
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login