Skip to content
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

Variable not recognized as string literal type when using ternary operator #12015

Closed
k8w opened this issue Nov 3, 2016 · 1 comment
Closed
Labels
Question An issue which isn't directly actionable in code

Comments

@k8w
Copy link

k8w commented Nov 3, 2016

TypeScript Version: 2.0.3 / nightly (2.1.0-dev.201xxxxx)
2.0.3

Code

function test(val: 'AAA'|'BBB'){
  //xxx
}

let a = true ? 'AAA' : 'BBB';
test(a);

Expected behavior:
Compiled successfully

Actual behavior:
Got error:

Error TS2345: Argument of type 'string' is not assignable to parameter of type '"AAA" | "BBB"'.

@k8w k8w changed the title Type not judged as string literal when using ternary operator Variable not recognized as string literal type when using ternary operator Nov 3, 2016
@kitsonk
Copy link
Contributor

kitsonk commented Nov 3, 2016

This has been discussed several times.

First, you are assigning to a let variable, which means the compiler will assume that you may want to change the value in the future, therefore it does not assign a string literal type to the variable.

Also, in 2.0, there was never an inference of literals. The developer would have to do that explicitly. So to fix this:

function test(val: 'AAA'|'BBB'){
  //xxx
}

let a: 'AAA' | 'BBB' = true ? 'AAA' : 'BBB';
test(a);

But in TypeScript 2.1 it will interpret assignments to const in the most strict way possible, so you could do it like this:

function test(val: 'AAA'|'BBB'){
  //xxx
}

const a = true ? 'AAA' : 'BBB';
test(a);

@k8w k8w closed this as completed Nov 21, 2016
@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Nov 21, 2016
@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