Basic Types

What

Basic types are the primitive building blocks of the TypeScript type system. They correspond directly to the primitive types found in JavaScript, such as strings, numbers, and booleans.

How

You declare a type by adding a : followed by the type name after a variable declaration:

const message: string = "starting server...";
const port: number = 3000;
const isOnline: boolean = true;
const noValue: null = null;
const notDefined: undefined = undefined;

Why

Explicitly typing primitives ensures that you don’t accidentally assign the wrong kind of data to a variable. If you try to assign a number to a string variable, TypeScript will throw a compilation error immediately:

const message: string = 123;
// Error: Type 'number' is not assignable to type 'string'.

Summary

By using basic types, you establish a baseline of safety for the most common data types in your application.