はじめに
自分用です
型
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}; // エラー出る
最後に
やったね!