?: / readonly Optional and readonly Properties
Last updated: 2026-10-22
?: / readonly Optional and readonly Properties
? marks a property optional (it may be absent); readonly marks it read-only (cannot be reassigned). The two most common modifiers on object properties.
| Group | Type Composition |
|---|---|
| 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
interface Config {
readonly name: string; // readonly: cannot be reassigned
retries?: number; // optional: may be absent
}
⚙️ Parameters
| ?: | Optional marker: the property may be omitted from object literals |
|---|---|
| readonly | Readonly marker: reassignment after initialization is a compile error (top level only) |
Returns:None — both modifiers are type-level only and vanish after compilation.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
shop localhost 8080
(Runtime output after transpilation; config.appName = "x" is a compile error — appName is readonly)
💡 Notes
ℹ️ Info Optional properties include undefined in their type: retries?: number is retries?: number | undefined under strict.
⚠️ Note readonly only blocks reassignment: readonly arr: number[] still allows push, and nested fields stay mutable. For deep immutability use Readonly<T> or as const.
💡 Tip Read optional properties with ?? defaults (config.port ?? 8080) instead of scattering undefined checks.
🏷️ Related Type Composition
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q readonly vs const?
A const guards the variable binding (no re-pointing); readonly guards a property (no reassignment). Fields of a const object stay mutable unless marked readonly.
Q Optional property vs T | undefined — any difference?
A Yes: ? allows the property to be absent entirely; a?: T | undefined requires presence but permits undefined. exactOptionalPropertyTypes enforces the distinction.
Q How to make an entire object (deeply) readonly?
A Readonly<T> is shallow; use as const (locks to literals) or a recursive DeepReadonly type for depth.