TS2361

error TS2361: The right-hand side of an ‘in’ expression must not be a primitive.

Broken Code ❌

1
2
3
4
5
import axios, {AxiosError} from 'axios';

const isAxiosError = (error: unknown): error is AxiosError => {
return 'isAxiosError' in error;
}

Fixed Code ✔️

You cannot use the in keyword on primitive data types. That’s why we have to replace the primitive type unknown with a non-primitive type like object:

1
2
3
4
5
import axios, {AxiosError} from 'axios';

const isAxiosError = (error: object): error is AxiosError => {
return 'isAxiosError' in error;
}

An alternative solution would be to use a type assertion on the right-hand side of the ‘in’ expression:

1
2
3
const isAxiosError = (error: unknown): error is AxiosError => {
return 'isAxiosError' in (error as AxiosError);
};