Closed
Description
Suggestion
🔍 Search Terms
chaining optional unknown
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Especially when catching an exception in try…catch but also in other places where the exact type may not matter it would be nice to be able to use some functions for a variable of type unknown
with optional chaining.
📃 Motivating Example
try {
// some code here that may throw an exception
} catch (exception) { // could be anything so it is unknown
// we might decide we don't care what type exception is only if it can be
// transformed to a string and if the string includes some text
if (exception?.toString().includes("HTTP 404")) {
console.log("uh oh");
}
}
instead of
try {
// some code here that may throw an exception
} catch (exception) { // could be anything so it is unknown
if (exception && typeof exception === "object" && exception.toString().includes("HTTP 404")) {
console.log("uh oh");
}
}
💻 Use Cases
I want to avoid writing extra type guards when not really needed so that I'm writing the same amount of code in TypeScript as I would if I were writing it directly in JavaScript.