I have an issue trying to properly type one of my function. In the following code, the type of x is any and I would like to type it better than that.
interface Pet {
name: string;
}
const checkType = (x: any): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}
I figure it out that unknown or object would be best fitted, but both give me an error as well
interface Pet {
name: string;
}
const checkType = (x: unknown): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}
Object is of type 'unknown'
interface Pet {
name: string;
}
const checkType = (x: object): x is Pet => {
return 'name' in x && typeof x.name === 'string';
}
Property 'name' does not exist on type 'object'
So my question is, how can I properly type x without casting to any ?
The following could be a soluce but I find it too much and specific :
interface Pet {
name: string;
}
const checkType = (x: object): x is Pet => {
return 'name' in x && typeof (x as {
name: unknown,
}).name === 'string';
}
More infos :
Example with any that could cause an issue :
