LoginSignup
2
3

More than 5 years have passed since last update.

Object.assign 引数5つ以上の any 戻り型を克服する

Last updated at Posted at 2018-10-12

引数5つ以上で any

libの定義にある通り、引数5つ以上の Object.assignany が戻り型となる。知らなかった。(thx: @k-okina

const ONE = { type: 'ONE' as 'ONE' };
const TWO = { type: 'TWO' as 'TWO' };
const THREE = { type: 'THREE' as 'THREE' };
const FOUR = { type: 'FOUR' as 'FOUR' };

const merged1 = Object.assign({}, ONE, TWO, THREE);
const merged2 = Object.assign({}, ONE, TWO, THREE, FOUR);
/** 【推論結果】 **/
const merged1: { type: 'ONE' } & { type: 'TWO' } & { type: 'THREE' }
const merged2: any

少し拡張する

定義されている ObjectConstructor に推論を追加する。tsconfig の include 相当の場所にあれば良い。

type UTI<T> = T extends any ? (args: T) => void : never
type UnionToIntersection<T> = UTI<T> extends (args: infer I) => void ? I : never
type ArgsIntersection<T> = T extends (infer I)[] ? UnionToIntersection<I> : never
interface ObjectConstructor {
  assign<T extends any[]>(...sources: T): ArgsIntersection<T>;
}

めでたし。

/** 【推論結果】 **/
const merged1: { type: 'ONE' } & { type: 'TWO' } & { type: 'THREE' }
const merged2: { type: 'ONE' } & { type: 'TWO' } & { type: 'THREE' } & { type: 'FOUR' }
2
3
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
2
3