1

I do programming with strikNullCheks option.

When I use ! operator with in operator, I got a following error. (This is exactly what happens when I use a payload of Redux's Action.)

Is there any way to solve the problem?

Thanks you for reading :)

interface Interface {
    AB?: {
        a: number;
    } | {
        b: number[];
    }
}

function test(ab: Interface['AB']) {
    const ab2 = ('a' in ab!) ? [ab!.a] : ab!.b;
    => error: Property 'a' does not exist on type '{ a: number; } | { b: number[]; }'. 
              Property 'a' does not exist on type '{ b: number[]; }'.
    => error: Property 'b' does not exist on type '{ a: number; } | { b: number[]; }'.
              Property 'b' does not exist on type '{ a: number; }'
}

example

1 Answer 1

3

The in type-guard (and generally type-guards) will not work on expressions. So the expression ab! will not result in the narrowing of ab. For the type-guard to work, the guarded expression must be a simple parameter/variable/field. The simplest solution is to guard against null explicitly. This is probably a good idea since the field is optional anyway:

function test(ab: Interface['AB']) {
    const ab2 = !ab ? null : ('a' in ab) ? [ab.a] : ab.b;
} 
Sign up to request clarification or add additional context in comments.

1 Comment

It helped. Thank you :D

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.