The code snippet above will not compile due to an error with the email protection link.
const foo: unknown = {bar: 'baz'}
if (foo && typeof foo === 'object' && 'bar' in foo) {
console.log(foo.bar)
}
An error message from TSC is:
Property 'bar' does not exist on type 'object'.
How can one convince tsc
that foo can have keys with arbitrary names without having to explicitly cast?
For a working example, check out this playground link. https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiEAuGBXMBrMIDuYYC8MA3gEYCGATigOQUBeNAvgFAsCWcMAFAiDADIBMKAE8ADgFMQXPoQJEaIUgCtJwKDUHC6VLe3x8AlCRYwYoSCAA2kgHTWQAc16I7FSkZZMgA