TS2638
Type
{}may represent a primitive value, which is not permitted as the right operand of theinoperator.
Broken Code ❌
try {
throw { status: 'error-test' };
} catch (error: unknown) {
if (error && 'status' in error) {
console.log(error.status);
}
}Fixed Code ✔️
When narrowing down the properties of error, it is important to first verify that error is an object and not a primitive value. Only then can we test if error has a property called status. If we skip the object check, error could be a primitive value, making the use of the in operator incorrect.
try {
throw { status: 'error-test' };
} catch (error: unknown) {
if (error && typeof error === 'object' && 'status' in error) {
console.log(error.status);
}
}