iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

TypeExample
string'Ada', "hi", `tpl ${x}`
number42, 3.14, 0xff
booleantrue, false
bigint9_007n
symbolSymbol('id')
null / undefinednull, undefined

Container types

ShapeExample
Arraynumber[] or Array<number>
Tuple[string, number]
Object{ id: number; name: string }
Function(x: number) => string
PromisePromise<User>
Map / SetMap<string, number> / Set<string>

Special types

TypeWhen to use
anyBail out of type checking. Treat like radioactive material.
unknown"I don't know yet" — like any but you must narrow before use.
voidFunction returns nothing meaningful.
neverFunction never returns (throws / loops forever).
objectAny 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'];

Test yourself

Q1. Which is NOT a primitive?
Q2. Array of numbers can be written as…
Q3. Function returning nothing useful is typed…

Discussion

Loading…