2017-03-08 4 views
0

오버로드 된 생성자가있는 클래스가 있습니다. 또한 클래스의 인스턴스를 반환하는 해당 클래스에 대한 팩토리 함수가 있습니다. 이 팩토리 함수도 오버로드되고 오버로드 된 생성자 구문에 의해 팩토리 함수의 모든 오버로드 구문이 일치됩니다.TypeScript : 동일한 오버로드 구문을 지원하는 클래스 생성자에 오버로드 된 함수의 전달 매개 변수

이제는 팩터 함수가 호출 된 인수를 생성자 호출에 '적용'하는 방법을 찾고 있는데, 팩터 함수와 생성자 사이의 논리를 복제하지 않고도 해당 함수의 유형을 공제 할 수 있습니다. 인수와 팩토리 함수에서 서로 다른 생성자 구문을 전환하고 구체적으로 호출합니다.

일부 코드는 위의 내용을 명확히 :

class X { 
    constructor() 
    constructor(noOfRows: number, noOfCols: number) 
    constructor(noOfRows: number, colNames: string[]) 
    constructor(????) { 
     //Logic here deduct based on the arguments send into the call which version of the constructor is called and properly initialize the X instance 
    } 


function createX(): X 
function createX(noOfRows: number, noOfCols: number): X 
function createX(noOfRows: number, colNames: string[]): X 
function createX(????): X { 
    //Here I rather not touch the arguments at all, but just forward them into the constructor call 
    return new X(????) 
} 

나는 다음과 같은 휴식/확산 방법 등 여러 가지를 시도했지만, 타이프 라이터는 그렇게하지 않습니다

function createX(...args: any[]): X { 
    return new X(...args) 
} 

하나를 이것을 (올바르게) 어떻게 할 것인가?

TIA,

+0

안녕 루세로, 나는 당신이 잘못 생각합니다. Javascript는 ES6 이후로 확산 구문을 사용하여이를 지원합니다. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Apply_for_new 이것은 스레드에서 암시되었습니다. 에 연결되어 있지만 그 대답은 어떤 upvotes도받지 못했다. – Paul

답변

0

는이 작업을 수행 할 수 있습니다 XConstructor를 내보내는 것은 아니지만

class X { 
    constructor(); 
    constructor(noOfRows: number, noOfCols: number); 
    constructor(noOfRows: number, colNames: string[]); 
    constructor(...args: any[]) { 
     // ... 
    } 
} 

interface XConstructor { 
    new (...args: any[]): X; 
} 


function createX(): X; 
function createX(noOfRows: number, noOfCols: number): X; 
function createX(noOfRows: number, colNames: string[]): X; 
function createX(...args: any[]): X { 
    return new (X as XConstructor)(...args); 
} 

(code in playground)

.
또 다른 옵션 :

class X { 
    constructor(); 
    constructor(noOfRows: number, noOfCols: number); 
    constructor(noOfRows: number, colNames: string[]); 
    constructor(a?: any, b?: any) { 
     // ... 
    } 
} 


function createX(): X; 
function createX(noOfRows: number, noOfCols: number): X; 
function createX(noOfRows: number, colNames: string[]): X; 
function createX(a?: any, b?: any): X { 
    return new X(a, b); 
} 

(code in playground)