Can I create a typeguard which asserts that a particular property exists (or has a specific type) in an object.
I.e
I have an interface Foo:
interface Foo {
bar: string;
baz: number;
buzz?: string;
}
Now an object of type Foo will have an optional property buzz. How would I write a function which asserts that buzz exists:
i.e
const item: Foo = getFooFromSomewhere();
if (!hasBuzz(item)) return;
const str: string = item.buzz;
How would I implement hasBuzz()?. Something along the lines of a typeguard:
function hasBuzz(item: Foo): item.buzz is string {
return typeof item.buzz === 'string'
}
Does something like this exist?
PS: I understand I can just do:
const item = getFooFromSomewhere();
if (typeof item.buzz === 'string') return;
const str: string = item.buzz;
But my actual use-case requires me to have a separate function which asserts the existence of buzz.