Object types — optional, readonly and index signatures¶
Level: 101 · for JavaScript programmers writing their first types
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: readonly on a property stops writes through that type only: assign the object to a variable typed { id: number } and loose.id = 2 compiles, changes the original, and tsc still rejects fixed.id = 3 as TS2540.
Keywords: optional property, index signature, readonly
What the finished page will answer¶
- Why does assigning a
{ readonly id: number }to a{ id: number }variable compile, and what does the original object hold afterloose.id = 2? - What is the difference between
label?: stringandlabel: string | undefined, and what doesexactOptionalPropertyTypesreport for{ label: undefined }(TS2375)? - What type does
scores["nobody"]have under{ [name: string]: number }, and what does it print? - Why does
{ [k: string]: number; name: string }fail with TS2411, and how do you type a record with one differently typed key? - Does
readonlyfreeze anything at run time, compared withObject.freeze?
Examples it will need¶
-
object_types_readonly_alias_sh.sh— tsc's TS2540 for the direct write and nothing for the write through a mutable alias, then Node printing the changed id -
object_types_optional_tserror.ts— TS2375 for{ label: undefined }underexactOptionalPropertyTypes, and TS2411 for a named property that breaks an index signature
See also¶
freeze,sealandpreventExtensions— the run-time lock thatreadonlyis not- Type aliases and interfaces — naming an object type once and reusing it
- Excess property checks — why an object literal with an extra key is refused
- Index access — index signatures that promise a value is present
readonlyandoverride— the same modifier on class fields- Rust:
Optionfields: modelling what may be absent ↗ — how Rust marks a field that may be missing