LoginSignup
14
6

More than 5 years have passed since last update.

TypeScript の Object.assign 型定義がガバガバだった

Posted at

TypeScript 2.8.0rc でも駄目でした。

事象

const x = {
    a: 1
}

const y = {
    a: "two"
}

const c = Object.assign({}, x, y);
c.a = ???; // a: number & string

Playground

本来なら c.astring となって欲しいが、 Object.assign の型定義が assign<T, U>(target: T, source: U): T & U; となっているせいで c.anumber & string となってしまう。

ネストしたオブジェクトでも & されるとそのプロパティがユニオンされてしまうので駄目

const x = {
    a: {
        b: 1
    }
}

const y = {
    a: {
        b: "two"
    }
}

const c = Object.assign({}, x, y);
c.a.b = ???; // b: number & string

Playground

解決方法

本家は issue は立っているが type spread の機能で解決しようとしているためまだ掛かりそう。
とりあえずは utility-types の Assign にキャストしてしまえば問題はない。

Object.assign({}, a, b) as Assign<typeof a, typeof b>

14
6
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
14
6