Madogiwa Blog

主に技術系の学習メモに使っていきます。

TypeScriptでClassのconstructorの引数の型を取得する方法MEMO

TypeScriptで普通の関数であればParameter<function>で関数の引数の型を取得できますが、Classのconstructorの引数の型を取得する方法がイマイチ分からず少しハマったのでやり方をメモ📝

Parameters
Constructs a tuple type from the types used in the parameters of a function type Type.
https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

結論としてはConstructorParameters<typeof Class>を使えば取得できた!

ConstructorParameters
Constructs a tuple or array type from the types of a constructor function type.
https://www.typescriptlang.org/docs/handbook/utility-types.html#constructorparameterstype

例えばVue 2からVue 3への移行したいときに、Vue 3に上げる前にnew Vue相当の処理をcreateAppを使って実装できる以下のようなWrapperを用意したりするときに型チェックも行えて便利!!

Vue2Wrapper

import Vue from "vue"; // Vue 2


export const createApp = (...args: ConstructorParameters<typeof Vue>) => {
  return new Vue(...args);
};

entry.ts

import { createApp } from "Vue2Wrapper"; 

const app = createApp({ /* ... */ });