TS Basic Types
TypeScript has a small set of built-in primitive types plus a handful of structural ones. Master these and you can describe most data you'll meet.
Primitives
| Type | Example |
|---|---|
string | 'Ada', "hi", `tpl ${x}` |
number | 42, 3.14, 0xff |
boolean | true, false |
bigint | 9_007n |
symbol | Symbol('id') |
null / undefined | null, undefined |
Container types
| Shape | Example |
|---|---|
| Array | number[] or Array<number> |
| Tuple | [string, number] |
| Object | { id: number; name: string } |
| Function | (x: number) => string |
| Promise | Promise<User> |
| Map / Set | Map<string, number> / Set<string> |
Special types
| Type | When to use |
|---|---|
any | Bail out of type checking. Treat like radioactive material. |
unknown | "I don't know yet" — like any but you must narrow before use. |
void | Function returns nothing meaningful. |
never | Function never returns (throws / loops forever). |
object | Any non-primitive. Usually you want a more specific shape. |
Where annotations go
TS
let name: string = 'Ada'; // variable
const ages: number[] = [36, 42]; // array
function add(a: number, b: number): number { return a + b; }
const greet = (name: string): string => `Hi, ${name}`;
class User {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
}
Tip: You rarely need to annotate every local variable. TS is great at inference. Annotate function parameters, return types, and module boundaries — let the body's locals stay inferred.
Example
Example
let id: number = 42;
let name: string = 'Ada';
let active: boolean = true;
let tags: string[] = ['admin', 'dev'];
let user: { id: number; name: string } = { id: 1, name: 'Ada' };
console.log(id, name, active, tags, user);
Try it Yourself »
Exercise
Array of strings using element-of-T notation.
let tags:
= ['admin', 'dev'];
string followed by square brackets.
Discussion
Loading…