Object Types

Describe the shape and give it a name. Then it can be used everywhere and changed in one place.

type and interface are largely interchangeable for object shapes. type also handles unions and everything that is not an object; interface can be reopened and added to later, which is useful for extending library types and surprising otherwise. Pick one convention per project and stop thinking about it.

Try it

Add a property that Book does not declare and read the error. Object literals are checked strictly on purpose, because an extra property is almost always a typo.

loading editor…

checking…

Two errors: readonly is enforced, and a required property cannot be left out. The second message names exactly which property is missing.

Structural typing: shapes match by shape, not by name. Anything with the right properties fits, whether or not it was declared as that type. A function taking { name: string } accepts a much larger object happily.

The exception is object literals, where extra properties are rejected. That inconsistency is deliberate: passing a variable that happens to have more is fine, but writing extra properties inline is nearly always a mistake.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Composing Types →
← Back