class Class Basics (accessors & static members)
Last updated: 2026-10-22
class Class Basics (accessors & static members)
A class bundles data and behavior: fields hold state, the constructor initializes, methods define behavior. new creates instances and this refers to the current one. TS layers field type annotations and compile-time checks on top of JS classes, so missing initializers and wrong arguments surface while you type.
| Group | Functions & Classes |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
class Book {
title: string; // field: explicit type
author: string;
copies: number;
constructor(title: string, author: string, copies = 1) {
this.title = title;
this.author = author;
this.copies = copies;
}
describe(): string {
return `${this.title} - ${this.author}`;
}
}
const book = new Book("The Three-Body Problem", "Cixin Liu", 3);
⚙️ Parameters
| constructor | Constructor: runs on new; responsible for initializing every field |
|---|---|
| describe(): string | Method: behavior living on the prototype; return type annotated explicitly |
Returns:Methods get explicit return types; the constructor takes none (it implicitly returns the new instance).
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
The Three-Body Problem - Cixin Liu (3 copies)
(Runtime output after transpilation; new Book("The Three-Body Problem", 123) is a compile error — the second argument must be string)
💡 Notes
ℹ️ Info Fields can be initialized at the declaration site (copies: number = 1), eliminating constructor assignments; the type can be inferred from the initializer.
💡 Tip Parameter properties are a TS feature: constructor(public title: string) declares the parameter and creates/initializes the field in one step, equivalent to this.title = title.
⚠️ Note With strictPropertyInitialization on, fields never assigned at declaration or in the constructor error; nullable fields take string | undefined, later-assigned ones use definite assignment (!).
🏷️ Related Functions & Classes
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Can field types be omitted?
A Yes when initialized at declaration (copies = 1 infers number); a bare declaration must be annotated or it is implicitly any.
Q Does the constructor have a return type?
A You neither write nor may write one — it implicitly returns the class instance. TS does not allow a return type annotation on a constructor; the type of a new expression is always the class instance.
Q What if this is lost inside a callback?
A Use arrow-function fields (say = () => this.x) or bind before passing; TS also supports a this parameter (fn(this: Book)) for compile-time enforcement.