Basic Types in TypeScript
Annotating strings, numbers, booleans, arrays, and letting TypeScript infer the rest.
2 min read
TypeScript's type system starts with the same primitive types JavaScript already has, plus a syntax for annotating variables, arrays, and more complex shapes with them.
Primitive type annotations
let username: string = "Ada";
let age: number = 36;
let isActive: boolean = true;The : type after a variable name is a type annotation — it tells TypeScript what values are allowed there. Assigning a mismatched value is a compile error:
let age: number = 36;
age = "thirty-six"; // Type 'string' is not assignable to type 'number'Note that, unlike some languages, TypeScript has a single number type covering all numbers — there's no separate int or float, matching JavaScript's own single numeric type underneath.
Type inference
Writing a type annotation on every single variable gets noisy fast, and TypeScript doesn't require it — it infers the type from the initial value whenever one is given:
let username = "Ada"; // inferred as string, no annotation needed
username = 42; // still a compile error -- inferred type is enforcedThe general rule: let TypeScript infer types where it obviously can (variables with an initial value), and write explicit annotations where it can't — function parameters, and variables declared without an initial value.
Arrays
let scores: number[] = [10, 20, 30];
let names: Array<string> = ["Ada", "Grace"];number[] and Array<number> mean exactly the same thing; [] syntax is more common in everyday code.
scores.push(40); // fine
scores.push("high"); // Argument of type 'string' is not assignable to parameter of type 'number'Object types
let user: { name: string; age: number } = { name: "Ada", age: 36 };Writing an object's shape inline like this works, but gets unwieldy for anything beyond a trivial shape — the next lessons cover interface and type, the two proper ways to name and reuse an object shape instead of repeating it inline everywhere.
any: the type that turns type checking off
let data: any = fetchSomeData();
data.whatever.you.want; // no error -- TypeScript stops checking this value entirelyany tells TypeScript to stop checking a value completely — it's occasionally necessary at the boundary with untyped JavaScript, but it's also a hole in the type system: an any value can be assigned to anything and accessed however you like, with zero compile-time safety. A later lesson compares it directly against unknown, a safer alternative for the same situation.
The next lesson moves from typing values to typing functions — parameters, return types, and the shapes a function itself can take.