A
A
Anton M2020-06-10 11:32:16
Data types
Anton M, 2020-06-10 11:32:16

What is the difference between primitive types and literal types?

TypeScript has primitive data types called literal data types. As the name suggests, types are expressed as value literals of primitive types.

I don't understand this idea at all. How would you explain?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
ned4ded, 2020-06-10
@Bluorenge

If a value is assigned to a type, it becomes a literal type.

type CarNames = 'bmw' | 'mercedes';

const cars: CarNames[] = ['bmw', 'mercedes', 'zhiguli'];
//                                            ^^^^^^^ 
//              TypeError: Type '"zhiguli"' is not assignable to type 'CarNames'.

More details and examples in the official documentation .
Accordingly, answering the first question: a literal type is a concrete value of one of the primitive types. Although the handbook talks about literal types only for strings and numbers, you can call "literal" the values ​​null, undefined, true, false, but this does not make much sense.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question