Lesson 3 / 1225%

Lesson 3

Basic Types

22 min

string, number, boolean, type inference, any and unknown.

What is a type?

Definition

A type is a label that describes the nature of a value (text, a number, a true or false...) as well as the set of operations you are allowed to perform with it. A number can be added, a text can be converted to uppercase: the type says what is allowed and what is not.

JavaScript already has types, but it only checks them when the program runs, which is often too late: the error happens on the user's side. TypeScript adds an extra step: it checks the types beforethe code runs, right in your editor. This lesson introduces the basic types, the ones you will use in absolutely all of your projects.

By the end of this lesson, you will know how to annotate a variable, recognize the primitive types, let TypeScript guess types for you, and above all avoid the trap of the any type.

Annotating a variable

In TypeScript, you indicate a variable's type with a colon after its name. This notation is called a type annotation. Once the type is set, TypeScript rejects any value of another type, and this rejection is shown immediately with a red underline in the editor, long before you run the program.

annotations.ts
let firstName: string = "Lea";
let age: number = 25;
let isStudent: boolean = true;

firstName = "Tom";     // OK
age = "twenty-five";   // Error: string is not assignable to number

The syntax is always the same: the keyword (letor const), the variable name, a colon, the type, and then optionally the value. In the example above, the line age = "twenty-five"is rejected because agewas declared as a number: you can't store text in it, even if that text looks like a number.

Screenshot of VS Code showing a TypeScript error for a variable assigned a value of the wrong type.

Primitive types

Primitive types are the simplest building blocks of the language: a primitive value is "raw" data that doesn't contain other values inside it. Here are the ones you will meet most often.

  • string: text, written between single quotes, double quotes or backticks (for example "Lea").
  • number: all numbers, integers or decimals (there is no separate int or float type). Special values like NaN("not a number") and Infinityare also of type number.
  • boolean: true or false. This is the type of conditions and switches.
  • null and undefined: the absence of a value, intentional or not.
  • bigint: integers of almost unlimited size, written with a trailing n(for example 9007199254740993n). Rarely useful at the beginning.
  • symbol: a unique identifier, used mostly by libraries. You will almost never need it.

An important point of attention: type names are written inlowercase. Forms likeStringor Numberwith a capital letter do exist, but they refer to wrapper objects that you don't use to annotate your variables. Always writestringand number.

Type inference

Good news: you almost never need to write types by hand. When you assign a value at declaration, TypeScript guesses the type on its own. This is called inference.

inference.ts
let city = "Lyon";       // TypeScript infers: string
let price = 19.99;       // number
let active = true;       // boolean

city = 42;               // Error: number is not assignable to string

const language = "TypeScript"; // literal type: "TypeScript"

Good to know

The common rule: let TypeScript infer when it's obvious, and annotate when the type can't be guessed (function parameters, a variable declared without a value).

Annotating function parameters

Inference can't guess the type of a function parameter, because TypeScript doesn't know in advance what values the function will be called with. This is therefore where annotations are essential. You can also annotate the type of the returned value, after the closing parenthesis.

functions.ts
function add(a: number, b: number): number {
  return a + b;
}

add(2, 3);      // OK: 5
add(2, "3");    // Error: string is not assignable to number

function greet(name: string): string {
  return "Hello " + name;
}

any: the type to avoid

The any type completely disables checking: the variable accepts anything, and you lose all the benefits of TypeScript. Use it only as a last resort.

any.ts
let data: any = "text";
data = 42;
data.nonExistentMethod(); // No error... but it crashes at runtime!

The danger of anyis that it is contagious: a value of type any, passed to a function or copied into another variable, carries this lack of checking everywhere it goes. A single misplaced any can make a whole part of the code fragile. If you catch yourself writing any to "silence" an error, it is almost always a sign that a better solution exists.

unknown: the safe alternative

When you truly don't know the type of a value (an API response, user input), use unknown. Unlike any, TypeScript forces you to check the type before using the value.

unknown.ts
let value: unknown = "hello";

// value.toUpperCase();  // Error: the type is unknown

if (typeof value === "string") {
  console.log(value.toUpperCase()); // OK: TypeScript knows it's a string
}

The typeofoperator is the basic tool for this check: it returns the name of the type as text ("string","number","boolean"...). Inside the if block, TypeScript "remembers" the result of the test and allows the operations specific to that type. This technique is called type narrowing.

Screenshot of VS Code showing a TypeScript error for a variable of type unknown used without a type check.

null, undefined and strict mode

With strict enabled, null and undefined are not accepted by default in another type. If a value can be missing, you have to say so explicitly (we will see unions in a later lesson).

strict.ts
let name: string = "Lea";
name = null;        // Error in strict mode: null is not assignable to string
name = undefined;   // Error in strict mode too

let grade: number;
console.log(grade); // Error: the variable is used before being assigned

This strictness is deliberate: the most frequent error in JavaScript is using a missing value as if it existed (the famous "cannot read properties of undefined"). Strict mode turns this runtime catastrophe into a simple warning at writing time. In a new project, you enable the"strict": trueoption in the tsconfig.json file, and you keep it enabled.

Summary

  • A type describes the nature of a value and the operations allowed on it.
  • You annotate with a colon:let age: number.
  • TypeScript infers types when the value is known at declaration: only annotate when necessary.
  • Function parameters must always be annotated.
  • Avoid any; prefer unknownfollowed by a check with typeof.
  • Keep strict mode enabled so thatnulland undefinedare handled rigorously.

Exercise

Declare three variables (a name, an age, a boolean) letting TypeScript infer the types. Then try assigning them a value of another type and observe the errors in VS Code. Next, write a function that takes two numbers and returns their product, then call it with a text to see the error. Finally, declare a variable of typeunknown and usetypeof to display its value in uppercase only if it is a text.