Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 4.9: Type 'NonNullable<K>' may represent a primitive value, which is not permitted as the right operand of the 'in' operator.(2638)

Typescript 4.9 features some changes to how the in operator works.

In the code snippet below, how do I convince tsc that id is not a primitive value?

export type KeyOrId =
  | {
      key: string;
    }
  | {
      id: string;
    };

export default function foo<K extends KeyOrId | null>(
  keyOrId: K,
) {
 
    if (!keyOrId) {
      return undefined;
    }

    // Type 'NonNullable<K>' may represent a primitive value, which is not permitted as the right operand of the 'in' operator.(2638)
    return 'id' in keyOrId;
}

I've tried a guard with typeof keyOrId !== 'object'. No dice.

Playground example

like image 622
wegry Avatar asked Oct 22 '25 06:10

wegry


1 Answers

This line is causing the issue - K extends KeyOrId | null .

K extends KeyOrId | null = K extends KeyOrId | K extends null .

The following should work -

export type KeyOrId =
  | {
      key: string;
    }
  | {
      id: string;
    };


export default function foo<K extends KeyOrId>(
  keyOrId: K | null,
) {
 
    if (!keyOrId) {
      return undefined;
    }

    return 'id' in keyOrId;
}
like image 140
Anmol Kansal Avatar answered Oct 23 '25 21:10

Anmol Kansal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!