Closed as not planned
Description
π Search Terms
ternary, conditional expression, recursion,
β Viability Checklist
- 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 isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
I propose that the following code should error
declare const b: boolean;
declare const a: any;
const s: string = b ? a : 42;
because number
is not assignable to string
.
This is already the case for the equivalent return statement "assignment", as of #56941.
function foo(b: boolean, a: any): string {
return b ? a : 42
}
So I think it would make sense to be consistent.
π Motivating Example
My real world code looked something like this
declare const x: unknown;
const s: string = x != null ? (x as any).prop : undefined
Another related example, is that this code should be an error
declare const a: any;
const s: string = a ?? 24;
Which relates to #51665 (comment), where an error should/would occur if the RHS of the ??
were checked separately.
π» Use Cases
- What do you want to use this for?
- Making less errors
- What shortcomings exist with current approaches?
- TS lets me make errors
- What workarounds are you using in the meantime?
- being sad
- avoiding
any
as much as possible