1. What is TypeScript?
TypeScript is an open-source language from Microsoft. It is a superset of JavaScript that adds an optional static type system. TypeScript code compiles to plain JavaScript.
Full lesson: Ts intro
46 questions about TypeScript with short answers and code. Each answer links to a full lesson on this site. Free, with no signup and no ads.
TypeScript is an open-source language from Microsoft. It is a superset of JavaScript that adds an optional static type system. TypeScript code compiles to plain JavaScript.
Full lesson: Ts intro
You install TypeScript with the npm tool. The global install command makes the tsc command available. Then you can check the version.
npm install -g typescript
tsc -v
Full lesson: Ts install
You compile a TypeScript file with the tsc command. The compiler writes a JavaScript file with the same name. Then you run the JavaScript file with node.
tsc Example.ts
node Example.js
Full lesson: Ts basic syntax
TypeScript has string, number, boolean, array, tuple, enum, and any types. Each type tells the compiler the shape of the data. A type annotation comes after the variable name.
let name: string = "Alice";
let age: number = 30;
let isDone: boolean = true;
Full lesson: Ts type
You write the variable name, a colon, and the type. You can use let, const, or var. The const keyword stops reassignment.
let count: number = 5;
const city: string = "Paris";
Full lesson: Ts variables
You add square brackets after the element type. You can also use the Array generic form. The array holds values of one type.
let sites: string[] = ["Google", "Example"];
let nums: Array<number> = [1, 2, 3];
Full lesson: Ts array
You put a type after each parameter name. You also put a type after the parameter list for the return value. The compiler then checks each call.
function add(a: number, b: number): number {
return a + b;
}
Full lesson: Ts function
You write the if keyword and a condition in parentheses. The code block runs when the condition is true. You can add else for the other case.
let score: number = 80;
if (score >= 60) {
console.log("Pass");
}
Full lesson: Ts if statement
A for loop has three parts in parentheses. The parts are the start, the condition, and the step. The loop repeats the block while the condition is true.
for (let i = 0; i < 3; i++) {
console.log(i);
}
Full lesson: Ts loop
You use the class keyword and a class name. The class holds fields, a constructor, and methods. You create an object with the new keyword.
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
Full lesson: Ts class
A subclass uses the extends keyword to inherit from a parent class. The subclass calls super() to run the parent constructor. The subclass can override parent methods.
class Animal {
speak(): void { console.log("sound"); }
}
class Dog extends Animal {
speak(): void { console.log("woof"); }
}
Full lesson: Ts class inheritance
You use the interface keyword and a name. The body lists the property names and their types. An object that matches the shape can use the interface as its type.
interface User {
id: number;
name: string;
}
let u: User = { id: 1, name: "Alice" };
Full lesson: Ts interface
You add the export keyword to a value in one file. Another file uses the import keyword and a path. Named exports use curly braces in the import.
// user.ts
export const name = "Alice";
// main.ts
import { name } from "./user";
Full lesson: Ts module
The compiler checks the type of each value. A string value does not match a number type. The fix is to change the value or the type annotation.
let age: number = 30;
age = "thirty"; // Error
Full lesson: Ts type
TypeScript rejects extra properties in a direct object literal. The object must match the interface exactly. The fix is to remove the extra property or add it to the interface.
interface User { id: number; }
let u: User = { id: 1, age: 30 }; // Error
Full lesson: Ts interface
The this keyword loses its class meaning inside a plain callback function. The callback runs with a different this value. The fix is to use an arrow function.
class Counter {
count = 0;
start(): void {
setTimeout(() => { this.count++; }, 100);
}
}
Full lesson: Ts class
You write a set of key-value pairs inside curly braces. The values can be strings, numbers, functions, or arrays. You then read a value with dot notation.
var sites = { site1: "Example", site2: "Google" };
console.log(sites.site1);
Full lesson: Ts object
You can use a string literal or the String constructor. A string literal creates the primitive string type. The literal form is the common and fast way.
const txt1: string = "Hello";
var txt2 = new String("string");
Full lesson: Ts string
You use the type keyword and give a name to an existing type. A type alias makes complex types shorter and easier to read. You can also give an alias to a union type.
type ID = string | number;
var uid: ID = 123;
Full lesson: Ts type alias
You set the type to a list of exact values. The variable can hold only one value from the list. A wrong value causes a compile error.
var direction: "up" | "down" = "up";
// direction = "upup"; // Error
Full lesson: Ts literal types
The any type skips all type checks. The unknown type is a safe any and needs a check before use. Use unknown when the type is not clear yet.
let a: any = 1;
let u: unknown = "text";
if (typeof u === "string") { console.log(u.length); }
Full lesson: Ts special types
The void type means the function returns no value. You use it as the return type of such a function. The function can still return undefined.
function logMsg(msg: string): void {
console.log(msg);
}
Full lesson: Ts special types
The never type means a value that never occurs. A function that always throws has the return type never. The never type is a subtype of all types.
function fail(msg: string): never {
throw new Error(msg);
}
Full lesson: Ts special types
You check the runtime type with a condition such as typeof. The compiler then knows the exact type inside that block. This lets you use type-specific properties in safety.
function len(x: string | number) {
if (typeof x === "string") { return x.length; }
return x;
}
Full lesson: Ts type guards
You use the built-in Partial utility type. Partial adds the optional modifier to every property. You can then pass an object with only some keys.
interface User { id: number; name: string; }
type PartUser = Partial<User>;
const u: PartUser = { name: "Alice" };
Full lesson: Ts utility types
You use the Pick utility type with the keys you want. Pick builds a new type from those keys only. The Omit type does the opposite and removes keys.
interface User { id: number; name: string; email: string; }
type NameOnly = Pick<User, "name">;
Full lesson: Ts utility types
You write a type that loops over the keys of another type. The in keyof syntax visits each property. You add readonly before the property name.
type ReadOnly<T> = { readonly [P in keyof T]: T[P] };
interface User { id: number; }
type RUser = ReadOnly<User>;
Full lesson: Ts mapped types
The function declares a return type but a code path returns nothing. The compiler checks every path against the return type. Add a return statement to each path.
function getNum(): number {
// missing return
}
// Error: lacks ending return statement
Full lesson: Ts function
The variable type includes undefined. The compiler blocks a method call on a value that can be undefined. Check the value first or use optional chaining.
let name: string | undefined;
// name.length; // Error
console.log(name?.length);
Full lesson: Ts type guards
A class that implements an interface must define every property and method. A missing member breaks the contract. Add the missing member or remove the implements clause.
interface IPerson { firstName: string; sayHi: () => string; }
class Person implements IPerson {
firstName = "Ann";
// sayHi is missing
}
Full lesson: Ts interface
The object type must match the declared interface exactly. A function property must have the same signature as the interface method. Fix the parameter list or the return type.
interface IPerson { sayHi: () => string; }
const c: IPerson = {
sayHi: () => "Hi"
};
Full lesson: Ts interface
A TypeScript program has three parts. It has statements, variables, and functions. The compiler runs the program from top to bottom.
let message: string = "Hello";
console.log(message);
Full lesson: Typescript basic structure
Use a for loop to repeat a block a fixed number of times. Use a while loop to repeat while a condition is true.
for (let i = 0; i < 3; i++) {
console.log(i);
}
Full lesson: Ts loop
Add a return type after the parameter list. The function must return a value of that type.
function add(a: number, b: number): number {
return a + b;
}
Full lesson: Ts function
An object type lists property names and their types. You can assign an object that matches the type.
let user: { name: string; age: number } = {
name: "Alice",
age: 30
};
Full lesson: Ts object
A type alias gives a name to a type. You can reuse the name in many places.
type Point = { x: number; y: number };
let p: Point = { x: 1, y: 2 };
Full lesson: Ts type alias
A literal type allows only a specific value. A union of literal types allows only those values.
let direction: "up" | "down" = "up";
direction = "left"; // Error
Full lesson: Ts literal types
A mapped type creates a new type from an old type. Add the readonly modifier in the mapping syntax.
type ReadonlyUser = {
readonly [P in keyof User]: User[P]
};
Full lesson: Ts mapped types
Partial<T> makes all properties of T optional. You can then create an object with only some properties.
interface User { id: number; name: string; }
type PartialUser = Partial<User>;
let u: PartialUser = { name: "Alice" };
Full lesson: Ts utility types
Omit<T, K> creates a type without the properties K. You can then create an object without those properties.
interface User { id: number; name: string; email: string; }
type NoEmail = Omit<User, "email">;
let u: NoEmail = { id: 1, name: "Alice" };
Full lesson: Ts utility types
Use the typeof operator in a condition. TypeScript then narrows the type inside the block.
function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
Full lesson: Ts type guards
A mapped type must use the correct syntax. A missing modifier or a wrong key type causes an error.
type Bad = { [P in keyof User]?: User[P] }; // correct
type Wrong = { [P in User]?: User[P] }; // Error
Full lesson: Ts mapped types
A literal type allows only the listed values. Any other value causes a compile error.
let status: "active" | "inactive" = "active";
status = "pending"; // Error
Full lesson: Ts literal types
A void return type means the function returns no value. Returning a value causes a compile error.
function log(): void {
return 1; // Error
}
Full lesson: Ts special types
The never type has no values. You cannot assign a never value to a number variable.
let n: never;
let x: number = n; // Error
Full lesson: Ts special types
A utility type expects a type that has the needed properties. A wrong type argument causes a compile error.
type Bad = Partial<number>; // Error
Full lesson: Ts utility types