3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScript: コンストラクタを受け取り、コンストラクタを返す関数

Posted at

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)
3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?