Use a static readonly property: class HttpClient { static readonly MAX_RETRIES = 3; }, read as HttpClient.MAX_RETRIES. The const keyword is not allowed on a class member (error TS1248), and any assignment to a readonly property fails with error TS2540. For an array or object constant add as const so its contents are readonly too, and Object.freeze when it must also hold at runtime.
TypeScript has no const for class members. The keyword that does the job is readonly: on a static property it gives you one named value per class, like public static final in Java or const in C#, and on an instance property it gives you a value that is fixed once the constructor has run. Two details trip people up. readonly is checked by the compiler and erased from the JavaScript, so nothing stops a write at runtime unless you freeze the object. And it is shallow: a readonly array can still be pushed to. The sections below cover both, plus the constants that are better kept outside the class. Each example runs on this page: hit Run, then edit the code and run it again.
1static readonly: a constant on the classRecommended
Declare the constant with static readonly and an initializer. static puts the property on the class itself, so every instance shares one value and you read it without creating an object. readonly lets it be assigned only where it is declared, and the compiler rejects every later write, even one from a static block inside the class. Add private for a constant only the class uses. Inside a static method, this is the class, so this.USER_AGENT works there; inside an instance method, go through the class name.
class HttpClient { // One value for the whole class, read-only after initialization static readonly MAX_RETRIES = 3; static readonly BASE_URL = "https://api.example.com"; private static readonly USER_AGENT = "compilebytes-demo/1.0"; describe(path: string): string { // Instance code reads a static through the class name, not this return `GET ${HttpClient.BASE_URL}${path} (retries: ${HttpClient.MAX_RETRIES})`; } static headers(): Record<string, string> { // In a static method, this is the class itself return { "User-Agent": this.USER_AGENT }; } } console.log(HttpClient.MAX_RETRIES); console.log(new HttpClient().describe("/users")); console.log(HttpClient.headers()); // readonly + a literal initializer keeps the literal type 3, not number const retries: 3 = HttpClient.MAX_RETRIES; console.log(typeof retries, retries);
Output
Prints 3, then GET https://api.example.com/users (retries: 3) and { 'User-Agent': 'compilebytes-demo/1.0' }. Writing this.MAX_RETRIES in describe instead fails with error TS2576: Property 'MAX_RETRIES' does not exist on type 'HttpClient'. Did you mean to access the static member 'HttpClient.MAX_RETRIES' instead? The last line, number 3, comes from a line that only compiles because a readonly property with a literal initializer keeps the literal type 3. A plain static TIMEOUT = 5000 widens to number, and assigning it to a variable typed 5000 gives error TS2322: Type 'number' is not assignable to type '5000'.
2Why not const? What the compiler rejects
The first thing everyone tries is const MAX_RETRIES = 3; inside the class body, or static const to match other languages. Both fail with error TS1248: A class member cannot have the 'const' keyword. const declares a variable, and a class body holds properties, so TypeScript uses readonly for them instead. The protection you get from it is a compile error on every write. This embed fails on purpose: the assignment stops the build, so nothing runs.
class HttpClient { static readonly MAX_RETRIES = 3; } // Raise the limit for one flaky endpoint? The checker refuses. HttpClient.MAX_RETRIES = 10; console.log(HttpClient.MAX_RETRIES);
Output
The compiler reports error TS2540: Cannot assign to 'MAX_RETRIES' because it is a read-only property. and the program never starts. The same error guards readonly instance fields when a method tries to change one. If one endpoint really needs a different limit, that isn't a constant: pass it as a parameter, or use a plain static property, which TypeScript lets you reassign.
3Array and object constants: readonly is shallow, as const is not
readonly stops you from pointing the property at a different value. It says nothing about the value itself, so an object or array behind a static readonly property can still be changed. Add as const to the initializer: every property becomes readonly, the array becomes a readonly tuple, and the values keep their literal types, which lets you derive a union type from the constant.
class Defaults { // readonly protects the property, not the object it points to static readonly OPTIONS = { retries: 3, verbose: false }; // as const makes every level readonly and keeps the literal types static readonly ROLES = ["admin", "editor", "viewer"] as const; static readonly LIMITS = { maxUsers: 10, maxProjects: 5 } as const; } Defaults.OPTIONS.retries = 10; // compiles: only the property is readonly console.log(Defaults.OPTIONS); // A union type straight from the constant: "admin" | "editor" | "viewer" type Role = (typeof Defaults.ROLES)[number]; function canEdit(role: Role): boolean { return role !== "viewer"; } for (const role of Defaults.ROLES) { console.log(role, canEdit(role)); } console.log(Defaults.LIMITS.maxUsers * Defaults.LIMITS.maxProjects);
Output
The first line, { retries: 10, verbose: false }, shows the shallow problem: the "constant" changed and the compiler said nothing. The as const members are locked down. Defaults.ROLES.push("guest") fails with error TS2339: Property 'push' does not exist on type 'readonly ["admin", "editor", "viewer"]'. and Defaults.LIMITS.maxUsers = 99 with error TS2540: Cannot assign to 'maxUsers' because it is a read-only property. The loop prints admin true, editor true, viewer false and the product is 50. More on (typeof X)[number] in create a union type from an array.
4Enforce it at runtime: Object.freeze and getters
readonly and as const only exist for the type checker; the JavaScript that runs is a plain writable property. That is enough inside one TypeScript codebase, but a cast, an any, or a plain JavaScript caller can still overwrite the value. If that matters, freeze it. A static { } block runs once while the class is defined, after the static fields above it, so Object.freeze(this) there locks the class's own properties. Freeze arrays and objects separately: Object.freeze is shallow too.
class Limits { static readonly MAX_ITEMS = 50; static readonly FORMATS = ["png", "jpg"] as const; } // readonly and as const are erased: code that gets past the types can write const loose = Limits as unknown as { MAX_ITEMS: number; FORMATS: string[] }; loose.MAX_ITEMS = 999; loose.FORMATS.push("gif"); console.log(Limits.MAX_ITEMS, Limits.FORMATS); class FrozenLimits { static readonly MAX_ITEMS = 50; static readonly FORMATS = Object.freeze(["png", "jpg"] as const); static { // Runs once, after the fields above: lock the class's own properties Object.freeze(this); } } const frozen = FrozenLimits as unknown as { MAX_ITEMS: number; FORMATS: string[] }; frozen.MAX_ITEMS = 999; // ignored here; strict-mode code throws console.log(FrozenLimits.MAX_ITEMS, Object.isFrozen(FrozenLimits)); try { frozen.FORMATS.push("gif"); // push on a frozen array always throws } catch (err) { console.log((err as Error).message); } // A getter-only static has no setter at all class Version { static get CURRENT(): string { return "2.1.0"; } } (Version as unknown as { CURRENT: string }).CURRENT = "9.9.9"; console.log(Version.CURRENT);
Output
The unfrozen class prints 999 [ 'png', 'jpg', 'gif' ]: both "constants" changed at runtime. The frozen one still prints 50 true. Its write was silently ignored because this page runs the compiled file as a sloppy-mode script; in strict-mode code (an ES module, a class body, or a build with alwaysStrict, which strict turns on) the same write throws a TypeError. Pushing to the frozen array throws everywhere: Cannot add property 2, object is not extensible. The getter-only Version.CURRENT still prints 2.1.0, because a property with no setter can't be assigned; the price is a function call on every read.
5readonly instance fields: a constant per object
Some values are fixed but differ per object: an invoice number, a user ID, the time an order was created. Leave out static and each instance gets its own readonly field, which may be assigned in its declaration or in the constructor and nowhere else. A parameter property, readonly net: number in the constructor parameters, declares the field and assigns it in one step.
class Invoice { static readonly TAX_RATE = 0.2; // one value for every invoice readonly number: string; // one value per invoice, fixed once set // A parameter property declares and assigns a readonly field in one go constructor(number: string, readonly net: number) { this.number = number; // the constructor may assign readonly fields } total(): number { return this.net * (1 + Invoice.TAX_RATE); } } const a = new Invoice("INV-001", 100); const b = new Invoice("INV-002", 250); console.log(a.number, a.total()); console.log(b.number, b.total()); console.log(Object.keys(a)); // instance fields live on each object console.log(Object.keys(Invoice)); // static fields live on the class
Output
The totals print INV-001 120 and INV-002 300. Object.keys shows where each kind lives: [ 'net', 'number' ] on every invoice, [ 'TAX_RATE' ] once on the class. With strict on, as in most projects, a readonly field that is declared but never assigned is an error: error TS2564: Property 'number' has no initializer and is not definitely assigned in the constructor. This page's compiler runs without strict, so there the field would just be undefined. For a value worked out from other fields on every read, use a getter instead (see use getters and setters).
6Constants that don’t need a class
A class only to hold constants is a habit from Java and C#. In TypeScript a module-level const (exported when other files need it) does the same job with less code. A group of related values fits in an as const object, frozen if it must hold at runtime, and an enum gives a named set that also exists at runtime. When you do want a constant to read as Palette.SECONDARY next to the class's own statics, a namespace with the same name as the class merges into it.
// A plain module-level const: no class needed const MAX_UPLOAD_MB = 25; // A frozen object of related constants; as const keeps the literal values const HttpStatus = Object.freeze({ OK: 200, NOT_FOUND: 404, SERVER_ERROR: 500, } as const); type StatusCode = (typeof HttpStatus)[keyof typeof HttpStatus]; function isError(code: StatusCode): boolean { return code >= 400; } // An enum: a named set of values that also exists at runtime enum LogLevel { Debug, Info, Warn, } // A class and a namespace with the same name merge: both sets of members class Palette { static readonly PRIMARY = "#3178C6"; } namespace Palette { export const SECONDARY = "#12161C"; } console.log(MAX_UPLOAD_MB * 1024 * 1024); console.log(HttpStatus.NOT_FOUND, isError(HttpStatus.NOT_FOUND), isError(HttpStatus.OK)); console.log(LogLevel.Warn, LogLevel[LogLevel.Warn]); console.log(Palette.PRIMARY, Palette.SECONDARY);
Output
Prints 26214400, then 404 true false: StatusCode is the union 200 | 404 | 500, so isError(418) wouldn't compile. The enum line is 2 Warn, since a numeric enum maps both ways (see loop through an enum), and the merged class prints #3178C6 #12161C. Namespaces still compile, but modern code prefers ES modules, so reach for the merge only when the Class.CONSTANT shape really matters.
7Which should you use?
| Approach | Checked by the compiler | Enforced at runtime | Best for |
|---|---|---|---|
| static readonly X = 3 | Yes (TS2540) | No | A constant that belongs to one class: the default |
| static readonly X = [...] as const | Yes, every level | No | Array and object constants; deriving union types |
| Object.freeze in a static block | Yes | Yes, one level | Libraries and values plain JavaScript can reach |
| static get X() | Yes | Yes (no setter) | Computed values; older code from before readonly |
| readonly x (instance) | Yes | No | A value fixed per object, set in the constructor |
| Module const / enum | Yes | The const binding only | Constants that don’t belong to one class |
Frequently asked questions
Why can't I use const inside a TypeScript class?
const declares a variable, and a class body declares properties, so TypeScript rejects it with error TS1248: A class member cannot have the 'const' keyword. The property equivalent is readonly: static readonly MAX = 3 for a constant shared by the class, or readonly max = 3 for one per instance.
What is the difference between readonly and const in TypeScript?
const is for variables: the binding can never be reassigned, and JavaScript enforces it at runtime. readonly is for properties: it may be assigned in its declaration or, on an instance field, in the constructor, and nowhere after, and only the type checker enforces it. Neither one makes an object or array immutable; use as const for the types and Object.freeze at runtime.
How do I access a static constant from an instance method?
Through the class name: HttpClient.MAX_RETRIES. this.MAX_RETRIES in an instance method fails with error TS2576: Property 'MAX_RETRIES' does not exist on type 'HttpClient'. Did you mean to access the static member 'HttpClient.MAX_RETRIES' instead? If subclasses override the constant and you want theirs, read it through the constructor: (this.constructor as typeof Base).LIMIT.
Why can't a subclass override my static readonly constant?
Because static readonly LIMIT = 3 has the literal type 3, and a subclass with static readonly LIMIT = 5 fails with error TS2417: Class static side 'typeof Sub' incorrectly extends base class static side 'typeof Base'. Annotate the base constant with the wider type, static readonly LIMIT: number = 3, and the override compiles.
Can an interface declare a static constant?
No: static readonly VERSION: string inside an interface fails with error TS1070: 'static' modifier cannot appear on a type member. An interface describes instances. Describe the static side in its own interface, interface Versioned { readonly VERSION: string }, and check the class against it with Api satisfies Versioned;. A class without the property fails with error TS1360.
How do I make a static constant private?
private static readonly SECRET = "…" hides it from other TypeScript code, but it is still a normal property in the JavaScript output. static readonly #SECRET = "…" is a JavaScript private field: it cannot be read from outside the class at runtime either, and Object.keys(Token) returns [].
Run it yourself
Open any of these in the full TypeScript editor to tweak, run and share.
TypeScript playground