LoginSignup
1
0

More than 3 years have passed since last update.

Typescript で スプレッド演算子を使った いわゆる mapping(copy) した時の注意点

Last updated at Posted at 2019-10-14

結論

見てもらったほうが速いので
実行環境をを示します。

実行環境はこちら

Typescriptを使って型mappingしたら 思っていた意図と違う結果が返ってきました。

型 Shipから 型 AnotherShip に内容をマッピングするという
単純なコードです

コード

Sorahune.ts
// 船
interface Ship {
    id   : number
    name: string
    cap: string
    member: string
}

interface AnotherShip {
    id   : number
    name: string
    member:string
}

const sorafune: Ship = {
    id: 1,
    name: "sonofune",
    cap: "omae",
    member:"TOKIO",
}

const map: AnotherShip = { ...sorafune }


//期待としては capというプロパティははなくなっていてほしい
console.log(map)

結果

javascriptにコンパイルされた結果は以下のようになってます。

Object.assainメソッド[mozilla]
を見ていただければわかるように、Objectを丸ごとコピーしており、
capプロパティは削除されていません。

Sorahune.js
"use strict";
const sorafune = {
    id: 1,
    name: "sonofune",
    cap: "omae",
    member: "TOKIO",
};
const map = Object.assign({}, sorafune);
console.log(map);

実際のコンソール画面です。

当たり前ですが、仮にmapping先(AnotherShip)に
Shipにないプロパティが存在していた場合、そこでコンパイルエラーになります。

ではでは。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0