?: / 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.

GroupType Composition
KindSyntax
Strict modeNot 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
readonlyReadonly 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏