Skip to content

Typing variables

von Schappler edited this page Oct 18, 2024 · 1 revision

Basic variable types

When writing JavaScript code, it's normal to simply declare a variable by giving it a name and it's initial value, like for example:

let name = 'Someone';

Because TypeScript is a superset over Javascript, any JavaScript code that we add inside a .ts will be "valid TypeScript" code as well.

When a variable is declared as above, TypeScript is able to infer which is the type of the declared variable. This means that TypeScript is alreayd doing it's work by setting a type specific value to a variable declared and if we try to assing something else to that variable that will show a TypeScript error.

// shows the TypeScript error - Type 'number' is not assignable to type 'string'
name = 5;

But even though TypeScript can automatically infer the type assigned to a variable, it's part of good practices to manually declare the type, by adding a colon after the variable name and a lower case version of the desired type, which would leads us to:

let name: string = 'SomeName';

Some other basic types that can be used are number and boolean

let name: string = 'SomeName';
let age: number = 10;
let isAdult: boolean = false;

Clone this wiki locally