Structural typing for objects
conforming to an object type: provide the required capabilities
- The object type is a contract specifying minimum capabilities.
- Conforming objects guarantee to have those properties and methods, so that one can reliably work with them.
- They can have unrelated, additional properties.
This behavior is called structural typing.
initialization with a literal: no unknown properties
When initializing with an object literal (fresh object literal), It is assumed that unknown properties at this stage are more likely to be errors or optional properties spelled with a typo. As such, TypeScript forbids the literal from having unknown properties. This is called "excess property check on fresh object literal".
In this example, it catches a misspelled property:
type BlogPost = {
title: string
subtitle?: string
}
const postA: BlogPost = {
title: "Understanding TypeScript Types",
subbtitle: "A practical introduction", // Object literal may only specify known properties, and 'subbtitle' does not exist in type 'BlogPost'.
}
assigning an existing object: unknown properties are ignored
The type-checker only checks if the existing object provides the properties and methods specified by the object type.
It ignores the other propertiesL
const draft = {
title: "Understanding TypeScript Types",
subtitle: "A practical introduction",
author: "Antoine",
}
const postB: BlogPost = draft
postB.title // "Understanding TypeScript Types",
postB.author // Error: Property 'author' does not exist on type 'BlogPost'