Skip to content

Separately check ternary branches for assignability #60813

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
6 tasks done
kirkwaiblinger opened this issue Dec 19, 2024 · 3 comments
Closed
6 tasks done

Separately check ternary branches for assignability #60813

kirkwaiblinger opened this issue Dec 19, 2024 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@kirkwaiblinger
Copy link

kirkwaiblinger commented Dec 19, 2024

πŸ” Search Terms

ternary, conditional expression, recursion,

βœ… Viability Checklist

⭐ 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

  1. What do you want to use this for?
    • Making less errors
  2. What shortcomings exist with current approaches?
    • TS lets me make errors
  3. What workarounds are you using in the meantime?
    • being sad
    • avoiding any as much as possible
@MartinJohns
Copy link
Contributor

Duplicate of #31518.

@kirkwaiblinger
Copy link
Author

kirkwaiblinger commented Dec 19, 2024

Duplicate of #31518.

Gotcha πŸ‘ Would just say that the only difference with this issue is that the context has now changed, due to #56941.

@typescript-bot
Copy link
Collaborator

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Jan 5, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants