Sub topic 1
Declaring classes and creating instances
Prerequisites
This chapter assumes you know the following:
- Basic TypeScript types and type annotations, such as
string,number, and function signatures. - JavaScript functions and objects, and a rough idea of what
thismeans inside a function. - The general idea of object-oriented programming: a class describes a kind of object, and an instance is one object of that kind.
Later chapters cover fields, constructors, methods, and access modifiers in detail. Here you only need the minimum to declare a class and create objects from it.
What a class declaration gives you
A class declaration introduces a name that works in two places at once.
class User {
name: string;
constructor(name: string) {
this.name = name;
}
greet(): string {
return `Hello, ${this.name}`;
}
}
const ada = new User("Ada");
const grace = new User("Grace");
console.log(ada.greet()); // Hello, Ada
console.log(grace.greet()); // Hello, GraceThe declaration has three parts:
- The
classkeyword and a name. By convention the name is PascalCase. - A
constructor, which runs once for eachnewcall and sets up the new object. - A method,
greet, which every instance can call.
The new operator creates a fresh object, runs the constructor with this bound to that object, and returns it.
Two sides of one name
The name User refers to two different things, and TypeScript tracks both.
| Position | What `User` means | Example |
|---|---|---|
| Type position (after `:`) | The type of an instance | `const u: User` |
| Value position (in an expression) | The constructor function | `new User("Ada")` |
The type of the constructor value is written typeof User. You need this when you pass the class itself around instead of an instance.
class User {
constructor(public name: string) {}
}
const Ctor: typeof User = User;
const copy: User = new Ctor("Grace");
function create(cls: new (name: string) => User, name: string): User {
return new cls(name);
}
console.log(copy.name); // Grace
console.log(create(User, "Linus").name); // LinusThe signature new (name: string) => User is a construct signature. It describes any value you can call with new that returns a User. Factory functions and dependency-injection code use it often.
How instances relate to each other
Each call to new produces a separate object with its own data. Methods are shared. They live once on the class's prototype, and every instance reaches them through the prototype chain.
class Counter {
count = 0;
increment(): void {
this.count++;
}
}
const a = new Counter();
const b = new Counter();
a.increment();
a.increment();
b.increment();
console.log(a.count, b.count); // 2 1
console.log(a === b); // false
console.log(a.increment === b.increment); // true
console.log(a instanceof Counter); // true
console.log(Object.getPrototypeOf(a) === Counter.prototype); // trueThe last three lines show the mechanism. The two instances are different objects, but they point at the same increment function through Counter.prototype. The instanceof operator checks whether Counter.prototype appears in an object's prototype chain.
Class expressions
A class can also be written as an expression and assigned to a variable. The name after class is optional.
const Greeter = class {
constructor(private greeting: string) {}
say(name: string): string {
return `${this.greeting}, ${name}`;
}
};
const g = new Greeter("Hi");
console.log(g.say("Ada")); // Hi, AdaDeclarations are the normal choice. Expressions are useful when you build a class inside a function or pass one as an argument.
What the compiler emits
TypeScript removes the type annotations and keeps the class. The output depends on the target option in tsconfig.json. With ES2015 or later, the compiled JavaScript still contains a native class. With ES5, the compiler rewrites the class as a constructor function and assigns methods to its prototype. The runtime behavior described above is the same in both cases.
The target also affects how fields are emitted. That topic is covered in the chapter on typing fields.
Common errors
Calling a class without new
A class is not an ordinary function. TypeScript reports the mistake at compile time.
class User {
constructor(public name: string) {}
}
// const u = User("Ada");
// Error: Value of type 'typeof User' is not callable. Did you mean to include 'new'?
const u = new User("Ada");
console.log(u.name); // AdaIf the error slips through, for example from untyped JavaScript, the runtime throws TypeError: Class constructor User cannot be invoked without 'new'.
Using a class before its declaration
Class declarations are hoisted, but they stay uninitialized until execution reaches them. This is the same temporal dead zone that applies to let and const.
// const early = new Late();
// Error: Class 'Late' used before its declaration.
class Late {}
const ok = new Late();
console.log(ok instanceof Late); // trueFunction declarations behave differently, because they are fully hoisted. Do not assume classes work the same way.
Mixing up the type and the value
Writing const x: User = User fails, because User as a value is the constructor, not an instance. Use typeof User for the constructor and User for the instance.
Structural compatibility
An object literal can satisfy a class type if it has the same public shape.
class Point {
constructor(public x: number, public y: number) {}
}
const p: Point = { x: 1, y: 2 }; // OK
console.log(p instanceof Point); // falseTypeScript accepts the assignment, but p was never created by new Point. The type check passes, and instanceof returns false. Use instanceof for runtime checks, because the type system alone cannot tell you how an object was built. The final chapter of this tutorial explains how private and protected members change this rule.
Summary of key points
class Name { ... }creates a constructor value and an instance type with the same name.newcreates an object, runs the constructor, and returns the object.- Instances have their own data and share methods through the prototype.
typeof Nameis the type of the class itself, andnew (...) => Namedescribes any constructible value.- Classes are not callable without
newand cannot be used before their declaration runs.
Exercise
Given class Box { constructor(public value: number) {} }, write a function makeAll that takes a class matching this constructor and an array of numbers, and returns an array of instances. Then explain why const b: Box = Box; does not compile.
Show answer
function makeAll(cls: new (value: number) => Box, values: number[]): Box[] { return values.map((v) => new cls(v)); } The call makeAll(Box, [1, 2, 3]) returns three Box instances. The assignment const b: Box = Box; fails because Box in a value position is the constructor function, whose type is typeof Box. The type Box describes an instance, so the two types are not compatible.
Exercise
In the Counter example, a.increment === b.increment is true while a.count === b.count can be false. Where is each one stored, and why?
Show answer
Each instance stores its own count as an own property, so the two values are independent. The increment method is stored once on Counter.prototype. Both instances find it through the prototype chain, so they get the same function object.