-1

Why tsc doesn't complain for this line of code:

let a: 'my text string';

and allows a to be of type 'my text string'?

And... Isn't this bug-prone if, let's say, someone takes advantage of implicit type inference, and just puts a ':' instead of '='?!

ebu_sho
  • 394
  • 6
  • 17

1 Answers1

1

This is a literal type. The documentation is here. An example:

type Color = 'blue' | 'red'

function showColor(c: Color) {
  console.log(c)
}

showColor('blue') // OK
showColor('other') // Error

Notice: Since TypeScript 2.0, literal types are expanded to numbers and booleans (not only strings). Then, with TypeScript 2.1, literal types are better inferred.


And... Isn't this bug-prone if, let's say, someone takes advantage of implicit type inference, and just puts a ':' instead of '='?!

In TypeScript, it's required to spot the :. The following code:

let a: 'my text string';

... is compiled to (here with the target ES6):

let a;
Paleo
  • 21,831
  • 4
  • 65
  • 76