Typescript behaving strangely when inferring function return type
Today I stumbled across a thing in typescript, where it was inferring the return type of a function with an if statement very strangely
Playgroundlink: https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcBGBDATgCkwLwC5EwQBbNAUywEpiBvRA40i6xAX0QB9F6v6AKESIA9KJGSRAPQD8wxDGCI8GfDT4KRWSlBBYk9AhwUntu-YZMnBoSLARNsBHCjgtyVWppHipiOQUlFTcNISkdPQM+NzNOBUjLPmsgA
Why is ts inferring the return type as
{foo?: undefined}
when its just {}
? When I type the return value explicitly it just does what you would expect it to do...TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
2 Replies
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Yeah that and {} is super lax and if you leave it to TS to figure out it's always going to be super accurate.
{} can be an array or a string for example but 'object' or {foo?: undefined} can't be