I encountered a recurring error that I managed to narrow down to a specific scenario which only occasionally replicates on the TypeScript Playground, but consistently fails when running tsc
locally.
type Result = {
success: true,
value: string,
} | {
success: false,
error: string,
};
const x = {success: true, value: 'hello'} as Result;
if (!x.success) {
console.log(x.error);
}
Access TypeScript Playground here
If you do not see the same error on TypeScript Playground, navigate to [TS Config] > and modify Target. It appears that changing it to "ES2017" or "ES2019" triggers the error for me.
https://i.sstatic.net/wMwi5.png
Inquiry:
(1) Should TypeScript be handling this issue, or is there an inherent problem with the approach in the code?
(2) Are there any effective workarounds aside from direct casting throughout the code?