TypeScriptでコンストラクタを受け取り、コンストラクタを返すジェネリックな関数を紹介する。
const constructorOf = <T extends new (...args: any[]) => U, U>(constructor: T): T => {
return constructor
}
使用例
class Point {
constructor(x: number, y: number) {}
}
const Point2 = constructorOf(Point) // ここ
const point = new Point2(1, 2)
動作確認
class Nullary {
constructor() {
}
}
class Unary {
constructor(public p1: 1) {
}
}
class Binary {
constructor(public p1: 1, public p2: 2) {
}
}
class Ternary {
constructor(public p1: 1, public p2: 2, public p3: 3) {
}
}
const nullary = new (constructorOf(Nullary))
const unary = new (constructorOf(Unary))(1)
const binary = new (constructorOf(Binary))(1, 2)
const ternary = new (constructorOf(Ternary))(1, 2, 3)
const assert = (predicate: boolean): void => {
if (!predicate) throw new Error()
}
const assertPropSize = (size: number, obj: any): void => assert(Object.keys(obj).length === size)
assertPropSize(0, nullary)
assertPropSize(1, unary)
assertPropSize(2, binary)
assertPropSize(3, ternary)
assert(unary.p1 === 1)
assert(binary.p1 === 1 && binary.p2 === 2)
assert(ternary.p1 === 1 && ternary.p2 === 2 && ternary.p3 === 3)