TIL about the useUnknownInCatchVariables compiler flag for TypeScript
🔗 a link post linking to www.typescriptlang.org
Today I was debugging a confusing situation.
- The variable inside a
catchstatement in TypeScript isanyby default, which is awful - Safari was throwing
undefinedwhen trying to place awebmfile into a<video>element, which was breaking my brain 🤯
I had mistakenly done this, assuming e would be an Error:
try {
putIntoVideoTag(file)
} catch (e) {
logger.error('What‽’, e.name, e.message)
}
So when e was undefined, it exploded.
One can manually type the catch variable so the compiler won’t let you
accidentally call e.name, like:
try {
putIntoVideoTag(file)
} catch (e: unknown) {
logger.error('What‽’, e)
}
But that means I can (and will) forget to do it.
Well, TIL that TypeScript now supports a flag to make all catch variables
default to unknown which is great: useUnknownInCatchVariables
It was added in the 4.4 release.
This is now the default in all my TypeScript projects ✨