TypeScript: reference
JavaScript with types: fewer errors, clearer code. A continuation of the JavaScript course.
Basics
What TypeScript adds
TypeScript is JavaScript with types. Type errors show up while you write the code, not in the browser.
let age: number = 16; let name: string = "Alex"; let ok: boolean = true; age = "sixteen"; // error: a string is not number
Compilation
The browser does not run .ts directly; the code is turned into JavaScript.
npm install -D typescript npx tsc --init # create tsconfig.json npx tsc # check and compile to JS
Types
Basic types and inference
Do not write a type where the compiler infers it itself. unknown is safer than any.
let n = 5; // the type is inferred: number let list: number[] = [1, 2, 3]; let pair: [string, number] = ["age", 16]; // tuple let anything: unknown = "text"; let id: string | number = 7; // union
Literal types and enum
A literal type allows only the listed values.
type Level = "easy" | "medium" | "hard";
let lvl: Level = "easy";
enum Color { Red, Green, Blue }
console.log(Color.Green); // 1Functions
Parameter and return types
The ? sign makes a parameter optional. void means that no value is returned.
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string, title?: string): string =>
title ? title + " " + name : name;
function log(msg: string): void { console.log(msg); }Interfaces and types
interface and type
An interface describes the shape of an object. For unions and simple aliases use type.
interface User {
id: number;
name: string;
email?: string; // optional field
readonly role: string; // read-only
}
type Point = { x: number; y: number };
const u: User = { id: 1, name: "Alex", role: "admin" };Extending and combining
extends adds fields to an existing interface.
interface Admin extends User {
permissions: string[];
}
type Result = Success | Failure; // one of twoType narrowing
typeof, in, checks
After the check the compiler knows a more precise type of the variable.
function show(v: string | number) {
if (typeof v === "string") {
return v.toUpperCase(); // here v is a string
}
return v.toFixed(2); // and here it is a number
}Generics
Generics
<T> is a type parameter: the function works with any type while keeping it.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(["a", "b"]); // string | undefined
interface Box<T> { value: T }Utility types
Partial, Pick, Record
Ready-made transforming types save you from describing new ones.
type UserPatch = Partial<User>; // all fields are optional
type Preview = Pick<User, "id" | "name">; // only the chosen fields
type Without = Omit<User, "email">; // all except the listed ones
const prices: Record<string, number> = { bread: 24 };Classes
Access modifiers
public, private and protected control access. public in a constructor creates the field right away.
class Account {
private balance = 0;
constructor(public owner: string) {}
deposit(sum: number): void {
this.balance += sum;
}
get total(): number { return this.balance; }
}Working with an API
A typed fetch
The compiler cannot check the server's response, so the type is stated explicitly (as) or the data is validated.
interface Item { id: number; title: string }
async function load(): Promise<Item[]> {
const res = await fetch("/api/items");
if (!res.ok) throw new Error("Error " + res.status);
return (await res.json()) as Item[];
}Learn TypeScript with practice
- 110 lessons, 80 of them base
- Tasks with in-browser code checking
- 3 projects from a specification, each requirement checked
- Free, nothing to install
Nearby in «Web technologies»: HTML · CSS · JavaScript
Better to know first: JavaScript