Home > OS >  "true" and "false" types in TypeScript
"true" and "false" types in TypeScript

Time:03-24

having this one

let toto: false
toto = true

let bibi: 5
bibi = 10

let titi: fakeType

I obtain these errors:
enter image description here

  • Type 'true' is not assignable to type 'false'.
  • Type '10' is not assignable to type '5'.
  • Cannot find name 'fakeType'. Did you mean 'KeyType'?
  • Exported variable 'titi' has or is using private name 'fakeType'.

Remarks and questions:

  1. toto variable, would seem to be an Union Type but by definition is should be formed from at least two type components..., in that case is only one...

  2. What for am I allowed to use a variable of constant value?

  3. If the type false or 5 I would create by using a 'literal' (or union type), why the error tells me about the types true or 10 I never created?

CodePudding user response:

Typescript allows to define literal types like this:

type Foo = "one" | "two" | "three";

which creates a type that only accepts one of those 3 strings.

You used this feature to declare a type that only accepts false as a value.

CodePudding user response:

You get an error on


let toto: false;

toto = true;

Because you are declaring the variable toto to be the type of false, so it can only accept false value:


toto = true; // error
toto = false; //ok

Please note the difference in : and =:

let foo: false
let bar = false

Here foo is declared as variable that can hold values of type false, that only include the literal false.

bar is assign the value of false, so the compiler automatically assign the type of boolean to bar

Typescript allows to the variables to be not only a type, but even a value type which means that variables can be of literal types:


let a: 1 | 2 = 1 // ok
a = 2 // ok
a = 3 // ERROR

This is to limit the values that a variables can hold, but this implies that a variables can be of type false for example.

And I agree, it is kind strange and useless having a variable that is of type false and only accept false, but it is the normal behavior that we have with const

A const variable is not the type of the literal, but the literal itself:

const a = 1 // here a is of type `1`

But this does not apply with expressions

const a = 1  1 // here a is of type `number`

EDIT:

to answer the final questions:

You could use constant as type in order to restrict the values that a variable can use:

let stringOrOne: string | 1 = "Hello"

if(typeof stringOrOne === "string") {
  console.log("I found a string")
}

stringOrOne = 1

if(stringOrOne === 1) {
  console.log("I found the number one")
}

This leads to a more complicated use case, for example to discrinated unions.


You get an error about the value true, because the true literal can not be assign to a variable of false type.

It is the same like assign a number to a string variable

let hello = "Hello"

hello = 0 // ERROR

Except that false type only accept false value.

  • Related