2017-05-23 2 views
1

일부 경우 구성 객체 내에서 제네릭을 사용할 때 유형이 캡처되지 않습니다. 특히typescript가이 제네릭 함수에서 내 형식을 캡처하지 않는 이유는 무엇입니까?

shouldBeInferedToBeANumber의 유형 number를해야한다 있도록 aNumber의 유형을 캡처해야 기능 functionAThatTakesAnObject하지만 대신이 유형 이유 {}

어떤 아이디어 주어진이야? 내가 여기서 무엇을 놓치고 있니? 이 항목이 bug입니까?

여기에 a typescript playground link입니다. 여기

그리고

코드입니다 :

function functionA<T>(funcThatReturnsT: (something: any) => T, funcThatTakeT: (t: T) => any) { 
    let something = undefined as any; 
    let hasTypeT = funcThatReturnsT(something); 
    return funcThatTakeT(hasTypeT); 
} 

let aNumber = 5; 

// works 
functionA(() => aNumber, shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential()); 
// still works 
functionA(_ => aNumber, shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential()); 

/** 
* this is the same as `functionA` but it takes a configuraton object instead 
*/ 
function functionAThatTakesAnObject<T>(opts: { 
    funcThatReturnsT: (something: any) => T, 
    funcThatTakeT: (t: T) => any 
}) { 
    let something = undefined as any; 
    let hasTypeT = opts.funcThatReturnsT(something); 
    return opts.funcThatTakeT(hasTypeT); 
} 

// works 
functionAThatTakesAnObject({ 
    funcThatReturnsT:() => aNumber, // if there is no parameter, it works 
    funcThatTakeT: shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential() 
}); 

// DOES NOT WORK 
functionAThatTakesAnObject({ 
    funcThatReturnsT: _ => aNumber, // if there is a parameter, it breaks 
    funcThatTakeT: shouldBeInferedToBeANumber => shouldBeInferedToBeANumber.toExponential() 
}); 

편집 : 내 댓글에서

설명 :

유형을 추론되지 않는 이유 부탁 해요. 나는 그 타입을 명시 적으로 말하고 싶지 않습니다. 일부 배경에서는 typescript에서 자바 스크립트 라이브러리를 작성하고 javascript 사용자는 해당 어설 션을 추가 할 수 없으므로 형식이 사용을 통해 유추되는 경우 유형 지정이 작동하는 유일한 방법입니다.

답변

1

고정, 그냥이 같은 유형 표시 : enter image description here

편집 : enter image description here

2 편집 : :이 (와 호환 만든이 또 다른 방법입니다

JS)

enter image description here

+0

타이코트면에서 오류를 없애 주므로 답변 해 주신 것에 감사드립니다. 그러나 형식이 유추되지 않는 이유는 무엇입니까? 나는 그 타입을 명시 적으로 말하고 싶지 않습니다. 일부 배경에서는 typescript에서 자바 스크립트 라이브러리를 작성하고 javascript 사용자는 해당 어설 션을 추가 할 수 없으므로 형식이 사용을 통해 유추되는 경우 유형 지정이 작동하는 유일한 방법입니다. –

+0

전달 된 매개 변수의 형식과 혼동을 일으키고 그 형식이 지정되지 않아 번호가 유추되지 않으며 번호 형식에 속하는 메서드가 실패합니다. @RicoKhler –

+0

나는 그것이 오류라고 말하지 않을 것입니다, 나는 그것이 논리적이라고 생각합니다. –

관련 문제