Nested Objects
A property can hold another object. A hero has a position on the map, with x and y. The type of such a property is an object type too:
type Hero = {
name: string;
position: { x: number; y: number };
};
const kira: Hero = { name: "Kira", position: { x: 3, y: 4 } };
kira.position.x = kira.position.x + 1;
console.log(kira);
console.log(kira.position.x);This prints:
{ name: "Kira", position: { x: 4, y: 4 } }
4Read kira.position.x from left to right: from kira, take position, an object with x and y, and from it x, a number. TypeScript checks the inner object as carefully as the outer one.
It's usually better to give the inner type its own name. The types get shorter, you can use the position elsewhere (a monster has one too, and so does a treasure), and the error messages get clearer. Compare the same mistake, a position without y, first with the type written inside Hero:
type Hero = { name: string; position: { x: number; y: number } };
const kira: Hero = { name: "Kira", position: { x: 3 } };main.ts(3,36): error TS2741: Property 'y' is missing in type '{ x: number; }' but required in type '{ x: number; y: number; }'.and then with a separate type Position:
type Position = { x: number; y: number };
type Hero = { name: string; position: Position };
const kira: Hero = { name: "Kira", position: { x: 3 } };main.ts(4,36): error TS2741: Property 'y' is missing in type '{ x: number; }' but required in type 'Position'.Notice the column, too. It points at position, the property with the inner object, not at the start of kira. When something is wrong deep inside an object, TypeScript shows you where. Reading a property that isn't there is reported with the inner type's name:
type Position = { x: number; y: number };
type Hero = { name: string; position: Position };
const kira: Hero = { name: "Kira", position: { x: 3, y: 4 } };
console.log(kira.position.z);main.ts(5,27): error TS2339: Property 'z' does not exist on type 'Position'.A property can hold an array too. A hero's inventory could be inventory: string[], a list of item names, or, with an Item type, inventory: Item[], a list of whole objects. Everything you know about arrays and objects works there as well: kira.inventory.push("rope"), kira.inventory.length, or a for...of loop over kira.inventory.
Instructions
- 1
Create a type
Weaponfor Kira's weapon, with the propertiesnameof typestringanddamageof typenumber. - 2
Create a type
Herowith the propertiesname(astring),position(aPosition) andweapon(aWeapon), and annotatekirawith it. - 3
Kira walks 3 steps east: at the end of the program, increase
kira.position.xby 3. Then print the line below, using the values inkira.position:Kira is at 5, 5 - 4
In a chest, Kira finds a better bow. Put a new weapon object into
kira.weapon: an Elven Bow with damage 12. Then print the line below, using the values inkira.weapon:Kira wields Elven Bow (12 damage)