Member-only story
Are We Saying Goodbye to Enums?
TypeScript 5.8 is here, and it brings some big changes! The two main updates are Granular Checks for Branches in Return Expressions and the new --erasableSyntaxOnly
flag. These changes help us write safer and cleaner code, and we might also be in very first stages of saying goodbye to enums!
TypeScript Trusted Us Too Much
Before TypeScript 5.8, return values in some conditional statements weren’t always checked properly. This could lead to weird bugs that only show up in runtime.
This code for example:
declare const untypedCache: Map<any, any>;
function getUrlObject(urlString: string): URL {
return untypedCache.has(urlString) ?
untypedCache.get(urlString) :
urlString;
}
As mentioned in docs, when TypeScript checks conditional expressions like cond ? trueBranch : falseBranch
, its type is treated as a union of the types of the two branches.
In above code, untypedCache.has(urlString)
going to be any
and urlString
having a string
type, and union of those going to be any
and as we all know, any can be a crazy witch!
Now, TypeScript handle this, checking both branches of the return statement. If one part returns something unexpected, it will do the complain!