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({ /* ... */ });