I have a TypeScript project and have defined a custom interface
interface Person {
name: string;
}
I would like to create a type guard for this interface that only returns true
if a value adheres to that interface. Specifically that it is...
- An Object
- with a
name
property - where the value of
name
is of typestring
I am able to accomplish 1 and 2 as follows:
const isPerson = (value: unknown): value is Person => (
value instanceof Object
&& 'name' in value
)
However if I try to check the type of value.name
...
const isPerson = (value: unknown): value is Person => (
value instanceof Object
&& 'name' in value
&& typeof value.name === 'string'
)
I receive the following error, highlighting .name
Property 'name' does not exist on type 'never'.ts(2339)
How can I create a type guard that ensures not only that a property exists but ALSO that the property is of a certain type?