Typescript: Variable not recognized as string literal type when using ternary operator

Created on 3 Nov 2016  ·  1Comment  ·  Source: microsoft/TypeScript



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"'.

Question

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:

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);

>All comments

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);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Gaelan picture Gaelan  ·  231Comments

kimamula picture kimamula  ·  147Comments

OliverJAsh picture OliverJAsh  ·  242Comments

fdecampredon picture fdecampredon  ·  358Comments

rbuckton picture rbuckton  ·  139Comments