Typescript 为包含泛型函数引用的变量声明类型
从本质上说,不是写作Typescript 为包含泛型函数引用的变量声明类型,typescript,typescript2.0,Typescript,Typescript2.0,从本质上说,不是写作 function test<T>(param: T): T { return param; } test<string>("xxx"); 值具有V类型,错误具有IErrors类型和onChange具有ChangeHandler类型 函数的预期类型为 export type FormEnhancer<V> = recompose.InferableComponentEnhancerWithProps<{}, Props&l
function test<T>(param: T): T {
return param;
}
test<string>("xxx");
值
具有V
类型,错误
具有IErrors
类型和onChange
具有ChangeHandler
类型
函数的预期类型为
export type FormEnhancer<V> =
recompose.InferableComponentEnhancerWithProps<{}, Props<V>>;
这并不能完全解决问题,因为我仍然能够写作
const raw = ({ foo }) => <input type="text" />;
const Wrapped = formEnhancer(raw);
constraw=({foo})=>;
const Wrapped=formEnhancer(原始);
这意味着TS无法推断目标的道具类型。
能够写一些像
function formEnhancer<V>(target: React.ComponentType<P extends Props<V>>) {
函数formEnhancer(目标:React.ComponentType){ 会有帮助的。
这对我很有用:const test = (<T>(param: T) => param);
const test=((param:T)=>param);
这将传递
X
的定义,该定义是任何返回与第一个参数相同类型的函数。我想您正在寻找:
function formEnhancer<V, P extends Props<V>>(target: React.ComponentType<P>): void {
...
}
函数formEnhancer(目标:React.ComponentType):void{ ... } 或者通过简短的例子:
class A<T> {
a: T;
}
class B<T> {
b: T;
}
function restricted1<P>(target: A<P>): void {
}
function restricted2<V, P extends B<V>>(target: A<P>): void {
}
let a1: A<number>;
let c: number;
let a2: A<B<number>>;
restricted1(a1); // succeeds
restricted1(c); // fails
restricted2(a1); // fails
restricted2(a2); // succeeds
A类{
a:T;
}
B类{
b:T;
}
功能受限1(目标:A
):无效{
}
功能受限2(目标:A
):无效{
}
设a1:A;
让c:数字;
设a2:A;
受限1(a1);//成功
受限1(c);//失败
受限2(a1);//失败
受限2(a2);//成功
我原以为它需要返回T,而不是param?这是什么意思?@AmmoGoettsch这是typescript中的一个通用标识函数示例。T不能返回,因为它是一个类型。我误读了你在那里写的函数类型decl,因为省略了返回和主体括号。我认为你在那里写的都是函数test(param:T){return param;}
这并不能解决所提出的问题。请看我的建议答案。@AmmoGoettsch,请看在前几行中,OP显示他不知道如何编写arrow泛型函数const test:X=(param)=>param;//如果你对这个问题的理解是正确的,那么这是一个有大量额外细节的琐碎问题。我选择相信这是一个更有趣的问题,即如何为一个函数编写一个签名,将其参数限制为特定泛型的特化。这实际上有点有趣,因此这是我的回答。也许我错了,但在OP问题的第一行,你可以看到他在问:在TS 2.5中是否有可能以非黑客的方式?…或者至少是黑客的方式?
。我直接回答了他。看起来他不知道如何在arrow函数中编写泛型。我认为他们唯一的问题是他们有e使其泛型具有两个模板参数,如我在示例中所示。这样,一个是基类型,另一个可以限制为扩展该基类型专用的其他泛型。这样,他们就得到了他们想要的。您的答案中没有回答这一问题。
const raw = ({ foo }) => <input type="text" />;
const Wrapped = formEnhancer(raw);
function formEnhancer<V>(target: React.ComponentType<P extends Props<V>>) {
const test = (<T>(param: T) => param);
function formEnhancer<V, P extends Props<V>>(target: React.ComponentType<P>): void {
...
}
class A<T> {
a: T;
}
class B<T> {
b: T;
}
function restricted1<P>(target: A<P>): void {
}
function restricted2<V, P extends B<V>>(target: A<P>): void {
}
let a1: A<number>;
let c: number;
let a2: A<B<number>>;
restricted1(a1); // succeeds
restricted1(c); // fails
restricted2(a1); // fails
restricted2(a2); // succeeds