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"'.
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);
Most helpful comment
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:
But in TypeScript 2.1 it will interpret assignments to
const
in the most strict way possible, so you could do it like this: