모든 생성자 매개 변수를 단일 개체로 허용하지 않는 한 원하는대로 할 수있는 방법을 생각할 수 없습니다 (적어도 우아하지는 않음).
(거의 잘) 다음과 제네릭을 사용하여 당신은 당신이 찾고있는 무엇을 달성 할 수있는 객체들 소품의 인터페이스를 강제 할 수 PARAMS 모든 클래스는 하나의 객체를 기대하는 경우 :
class Base<T> {
constructor(props: T) {}
}
type BaseConstructor<C extends Base<P>, P> = {
new(props: P): C;
}
interface AProps {}
class A extends Base<AProps> {}
interface BProps {
x: number;
y: number;
}
class B extends Base<BProps> {}
interface CProps {
str: string;
ok?: boolean;
}
class C extends Base<CProps> {}
function createClassFactory<C extends Base<P>, P> (MyClass: BaseConstructor<C, P>) {
return function classFactory(props: P) {
return new MyClass(props);
}
}
// the following are valid:
let a1 = createClassFactory(A)({});
let b1 = createClassFactory(B)({ x: 3, y: 5 });
let c1 = createClassFactory(C)({ str: "stirng" });
let c2 = createClassFactory(C)({ str: "stirng", ok: true });
// these aren't:
let b2 = createClassFactory(B)({ x: 3, y: "5" });
let c3 = createClassFactory(C)({ ok: true });
// but this one is:
let a2 = createClassFactory(A)({ key: "value" });
(code in playground)
비어 있지 않은 객체로 a2
이 생성 된 마지막 예제로 인해 거의 말합니다.
하지만 그 외에도 당신이 요구 한 것은 꽤 많이 있다고 생각합니다.
variadic 종류에 대한이 [제안] (https://github.com/Microsoft/TypeScript/issues/5453)이 구현 된 경우이 작업을 수행 할 수 있습니다. – calebboyd