Is there a way to type guard an unknown type in TypeScript?
const foo = (obj: unknown) => {
if (typeof obj === 'object' && obj) {
if ('foo' in obj && typeof obj.foo === 'string') {
return obj.foo;
}
}
};
However, I am encountering an issue
Property 'foo' does not exist on type 'object'.
I also tried using the is expression but it doesn't work as expected:
const foo = (obj: unknown): obj is { foo: 'string' } => {
if (typeof obj === 'object' && obj) {
if ('foo' in obj && typeof obj.foo === 'string') {
return obj;
}
}
throw new Error();
};