LoginSignup
8
7

More than 5 years have passed since last update.

TypescriptでObject.assignでobjectのcopyを作ってるなら今すぐ変えたほうが良い

Last updated at Posted at 2018-10-11

はじめに

自分用です

Objectのassignの型


     /**
     * Copy the values of all of the enumerable own properties from one or more source objects to a
     * target object. Returns the target object.
     * @param target The target object to copy to.
     * @param sources One or more source objects from which to copy properties
     */
    assign(target: object, ...sources: any[]): any;

戻り値がanyだ。。。と。。。!?

つまり、以下のコードがコンパイルで通ってしまう。


type A = { id: 'hello', name: 'abc' };
type B = { id: 'world', age: string };
let hoge: A = { id: 'hello', name: 'abc' };
let fuga: B = { id: 'world', age: 'abc' };

let piyo: A = Object.assign({}, fuga); // 通る

改善

スプレッド演算子ならちゃんと型安全にイケるみたい

type A = { id: 'hello', name: 'abc' };
type B = { id: 'world', age: string };
let hoge: A = { id: 'hello', name: 'abc' };
let fuga: B = { id: 'world', age: 'abc' };

// let piyo: A = Object.assign(fuga);
let piyo: A = {...fuga}; // エラー出る

最後に

やったね!

8
7
0

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
8
7