項目21 オブジェクトを一度に構築する
オブジェクトは段階的に構築するより、一度に構築するようにする
段階的に構築すると、一番最初に作成した型が維持されてしまうため
code:ts
const pt = {};// ^? const pt: {}
pt.x = 3;// ~ Property 'x' does not exist on type '{}'
pt.y = 4;// ~ Property 'y' does not exist on type '{}'
名前付き型を使ったオブジェクトの構築
オブジェクトを一度作って、型アノテーションを付与するのがベスト
code:ts
const pt: Point = {x: 3, y: 4};
小さいオブジェクトから大きオブジェクトを構築する場合も、段階的に行うのは避けるべき
code:ts
const pt = {x: 3, y: 4};
const id = {name: 'Pythagoras'};
const namedPoint = {};
Object.assign(namedPoint, pt, id);
namedPoint.name;// ~~~~ Property 'name' does not exist on type '{}'
大きオブジェクトの構築にはスプレット構文を使う
code:ts
const namedPoint = {...pt, ...id};//const namedPoint: { name: string; x: number; y: number; }
namedPoint.name; // OK
オブジェクトに新しいプロパティを追加して、新しい型を推論させるテクニック
更新のたびに、新しい変数を生成するのがポイント
code:ts
const pt0 = {};
const pt1 = {...pt0, x: 3};
const pt: Point = {...pt1, y: 4}; // OK
条件付きプロパティの追加を型安全に行う
スプレッド構文で{}または任意の偽値(null, undefined, false)などを使う
code:ts
declare let hasMiddle: boolean;
const firstLast = {first: 'Harry', last: 'Truman'};
const president = {...firstLast, ...(hasMiddle ? {middle: 'S'} : {})};
// ^? const president: {
// middle?: string;
// first: string;
// last: string;
// }
//または
const president = {...firstLast, ...(hasMiddle && {middle: 'S'})};