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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With