non-overlapping cast error should suggest casting to the narrowest possible type instead of `unknown`
See original GitHub issueSuggestion
🔍 Search Terms
overlap cast error unknown conversion
List of keywords you searched for before creating this issue. Write them down here so that others can find this suggestion more easily and help provide feedback.
✅ 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
given the following three types: A
, B extends A
and C extends A
, this error message could be improved if instead it suggested the narrowest common ancestor type instead of unknown
before:
Conversion of type ‘B’ to type ‘C’ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘unknown’ first.
after:
Conversion of type ‘B’ to type ‘C’ may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to ‘A’ first.
📃 Motivating Example
interface A {
a: number
}
interface B extends A {
b: number
}
interface C extends A {
c: number
}
interface D {
d: number
}
declare const foo: B
// Conversion of type 'B' to type 'C' may be a mistake because neither type sufficiently overlaps with the other.
// If this was intentional, convert the expression to 'unknown' first.
foo as C
//when using unknown, it's easier to accidentally cast to a completely unrelated type:
foo as unknown as C
foo as unknown as D //no error
//when using A, you get an error if you do that:
foo as A as C
foo as A as D //error
💻 Use Cases
- makes casting a little bit safer
- helps users learn the casting rules more easily
- when i was new to typescript i had no idea why casting to
unknown
fixed these overlapping type errors, and i think many users probably feel the same and just blindly follow the suggestion in the error message without having a clear understanding of what it means
- when i was new to typescript i had no idea why casting to
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:6 (4 by maintainers)
Top GitHub Comments
Not looking onto the feasibility side, if the cast is between non-overlapping ones, isn’t it already straight unsafe?
Reference link: diagnostic message ts(2352) (
diagnosticMessages.json#L1815-L1817
) (aka TS2352)