Skip to content

A conditional operator literal string type problem #14204

New issue

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

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

Already on GitHub? Sign in to your account

Closed
BirdLeeSCUT opened this issue Feb 21, 2017 · 2 comments
Closed

A conditional operator literal string type problem #14204

BirdLeeSCUT opened this issue Feb 21, 2017 · 2 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@BirdLeeSCUT
Copy link

BirdLeeSCUT commented Feb 21, 2017

TypeScript Version: 2.1.5

There is a conditional operator literal string type problem, ts cannot resolve true ? "a" : "b" as a type, which may call some errors.

for example:

type a_or_b = "a" | "b" ;
let v1 = (true ? "a" : "b");
let v2: a_or_b;
v2 = v1; // ERROR

Expected behavior:
expect no error.

Actual behavior:
but it comes up with an error as follow:
TS2322
image

I know a solution to refrain this error is changing the line 2 to be let v1: any = (true ? "a" : "b"); or let v1: a_or_b = (true ? "a" : "b"); , but this procedure seem to should be needless.

@krryan
Copy link

krryan commented Feb 21, 2017

Try const v1 = (true ? "a" : "b");. Since you are using let you are allowing v1 to be reassigned and the compiler assumes you want it to accept the wider range of values (string), but with const it can be narrower.

(What actually surprises me here is that it infers the type of const v1 as "a" | "b" rather than "a" which is clearly the only thing it can actually be; I made a separate bug for that)

@mhegazy mhegazy added the Question An issue which isn't directly actionable in code label Feb 21, 2017
@BirdLeeSCUT
Copy link
Author

@krryan Thanks, it works well!

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

3 participants