These are the types you use constantly. They form the building blocks for everything else. (Source: Everyday Types.)
The primitives: string, number, and boolean
Same names you get from JavaScript's typeof:
string:"Hello, world"number:42(no separateint/floatin JavaScript)boolean:trueorfalse
Always use the lowercase forms. String, Number, and Boolean (capitalized) refer to special wrapper types you almost never want.
let username: string = "Alice";
let age: number = 26;
let isAdmin: boolean = false;
Arrays
For [1, 2, 3], write number[]. Same idea for any element type:
const scores: number[] = [90, 85, 100];
const names: string[] = ["Alice", "Bob"];
Array<number> means the same thing (T[] vs Array<T>). You will see both.
Note: [number] is a tuple shape (one-element tuple), not "array of numbers". Prefer number[] for lists.
any
any opts out of type-checking for a value. You can do almost anything with it : and TypeScript will not complain:
let obj: any = { x: 0 };
obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n: number = obj;
None of those lines error at compile time. Use any sparingly: when you are prototyping, dealing with untyped data, or bridging legacy code. Prefer real types as soon as you can.
noImplicitAny
If you omit a type and TypeScript cannot infer one, it may default to any. With noImplicitAny (part of strict), that becomes an error so you notice.
Type annotations on variables
Annotations go after the name:
let myName: string = "Alice";
TypeScript does not use C-style string myName = "Alice".
Most of the time, skip the annotation when the initializer is clear:
let myName = "Alice"; // inferred as string
Start with fewer annotations than you think you need. Add them where inference is weak (function parameters, empty arrays, complex objects).
Quick reference
| TypeScript | Example values |
|---|---|
string |
"hi", `template` |
number |
0, 3.14 |
boolean |
true, false |
string[] |
["a", "b"] |
any |
anything (unchecked) |
Practice
let title: string = "Full Stack";
let lessonCount: number = 10;
let published: boolean = true;
let tags: string[] = ["typescript", "types"];
// Which of these should be an error?
title = 42;
lessonCount = "ten";
tags.push(1);
Fix the types or the assignments until tsc is clean.