Types and inference

Use the primitive types

Describe string, number, boolean, bigint, symbol, null, and undefined values with lowercase TypeScript type names.

JavaScript has seven primitive value types, and TypeScript has a lowercase type name for each one. The three you use every day are string, number and boolean:

const title: string = 'TypeScript Course'
const lessons: number = 42
const published: boolean = true

Inference would give these the same types without the annotations. I wrote them out here so you can see the names.

Each name accepts only its own kind of value. Give a string to a number and the compiler stops you:

const lessons: number = '42'
error TS2322: Type 'string' is not assignable to type 'number'.

Lowercase, not capitalized

Be careful with the casing. Write string, number and boolean, never String, Number and Boolean. The capitalized names exist, but they describe the wrapper objects JavaScript creates when you call new String('hello'). Those objects almost never belong in application code.

TypeScript tells you so if you mix them up:

const title: string = new String('TypeScript Course')
error TS2322: Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.

Your editor may autocomplete the capitalized version. Pick the lowercase one.

One number type

JavaScript has a single number type for integers and floating-point values. 42 and 3.14 are both number. TypeScript does not add int, float or double. It cannot, because those distinctions do not exist at runtime, and types are erased before the program runs.

If you need integers larger than 2^53, JavaScript has bigint, written with an n suffix:

const big: bigint = 9007199254740993n

The n literal needs a compiler target of ES2020 or newer. The tsconfig.json we create later in the course sets that.

The other primitives

The remaining primitive types are symbol, null and undefined. You rarely annotate a symbol by hand. null and undefined come up constantly, and they deserve their own lesson, which arrives a few lessons from now.

For now, know that with strict checking a string is only a string. It does not silently accept null or undefined. If a value can be missing, you say so in the type, like string | undefined. This is one of the main reasons TypeScript catches so many crashes.

A type describes which values are allowed. It does not change how those values behave in JavaScript. '42' + 1 is still '421' at runtime, whether or not you annotated anything.

Try this on your own: declare one value with each lowercase primitive type. Then replace string with String on one of them, hover over it, and read the error before switching back.

Lesson completed