2017-04-23 5 views
0

result2와 같은 결과로 유형을 가져와야합니다. 함수를 변경하여 어떻게 든 해결할 수 있습니까? getNestedProperty?큰 중첩을 사용하여 올바른 유형을 얻을 수 있습니까?

interface ILevel3 { 
    level3:() => void; 
} 

interface ILevel2 { 
    level2: ILevel3; 
} 
interface ILevel1 { 
    level1: ILevel2; 
} 

const bigNestedObject: ILevel1 = { 
    level1: { 
    level2: { 
     level3:() => {} 
    } 
    } 
}; 

const result = getNestedProperty(bigNestedObject)('level1.level2.level3'); 
result(); // error type object 

const result2 = bigNestedObject.level1.level2.level3; 
result2(); // it's ok type =() => void 

const getNestedProperty = (root: object) => (propertyString: string): object => { 
    return propertyString 
      .split('.') 
      .reduce(<R, KPath extends keyof R>(acc: R, current: KPath): R[KPath] => acc[current], root); 
} 

은 내가 결과 유효 유형 =() => 무효로받을 수 있습니까?

답변

1

코드 재 배열을 시도해 볼 수 있다고 생각합니다. const getNestedPropertygetNestedProperty을 블록 범위 변수로 만듭니다. 따라서 사용하기 전에 변수를 선언해야합니다.

고차 함수로 만든 함수의 최종 반환 형식은 호출 서명이없는 object 유형입니다. 따라서 리턴 된 함수 오브젝트를 호출하려면 asFunction으로 변환하는 것이 유용 할 수 있습니다. 이 도움이

//omitting interfaces for brevity 

const bigNestedObject: ILevel1 = { 
    level1: { 
    level2: { 
     level3:() => { 
     console.log("Hello World"); 
     } 
    } 
    } 
}; 

function core<R, KPath extends keyof R>(acc: R, current: KPath): any { 
    return acc[current]; 
} 

const getNestedProperty = (root: object) => (propertyString: string): object => { 

    //the core function can also be defined here inside getNestedProperty 

    return propertyString 
      .split('.') 
      //.reduce(<R, KPath extends keyof R>(acc: R, current: KPath): R[KPath] => acc[current], root); 

      //the old commented code should also work, 
      //but note this makes the code easier to read. 
      .reduce(core, root); 
} 

const result = getNestedProperty(bigNestedObject)('level1.level2.level3'); 
console.log(result); // [Function: level3] 

const result2 = bigNestedObject.level1.level2.level3; 
console.log(result2); // [Function: level3] 

(result as Function)(); //Hello World 

희망 :

다음은 완전한 예입니다.


업데이트 : 코드 위의 변경 아래 Aluan Haddad에 의해 제안 당 엉덩이 댓글을 달았습니다. 새로운 core 함수 (더 나은 이름 찾기)가 추가되어 코드를 더 이해하기 쉽게 만듭니다. 이전 코드는 주석으로도 작동해야합니다.

+0

+1. reduce 함수를 중첩 함수 나 가독성을위한'const' 선언으로 추출 할 것을 제안 할 수 있습니까? –

+0

@AluanHaddad 귀하의 제안에 감사드립니다. 실제로 가독성을 향상시킵니다. 그러나 코드는 OP에서 가져온 것이므로 문제를 일으키지 않는 현재 상태로두고 싶습니다. 코드를 검토하지 않고 문제 해결을위한 솔루션을 제공합니다. 당신이 이해하기를 바랍니다. –

+0

나는 좋은 가정을 설정하는 것이 좋다고 생각한다. –