可以推断在参数的通用接口中使用的类型吗?
Possible to infer type used within a generic interface of a parameter?
我有这个方法:
attachTheme<TTheme, TSelector>(config: IConfig<TTheme, TSelector>): OtherClass<TSelector> {
}
IConfig:
interface IConfig<TTheme, TSelector> {
select(theme: TTheme): TSelector;
}
我想这样使用:
attachTheme<MyTheme>({ select: theme => ({ background: theme.scroller.background }) });
return 值是用 { background: string; }
键入的,但是如果我没有指定默认的 TSelector,它会抱怨,所以如果我把 {}
作为默认值,输出的通用类型是 {}
,尽管我觉得它应该推断类型。
我已经研究了 infer
关键字,但无法让它发挥作用,我觉得我对它的理解还不够深入,无法以正确的方式使用它,我希望有人会比我更好地理解它来解决我的问题吗?关于关键字的内容似乎很少,关于如何使用它的示例也更少。
最简单的解决方案是让编译器通过将主题指定为箭头函数参数的类型注释来推断这两个参数
attachTheme({ select: (theme: MyTheme) => ({ background: theme.scroller.background }) });
如果您不想在 3.1 中执行此操作,我们将得到 Named type arguments & partial type argument inference
另一种解决方案是使用返回函数的函数来指定一个参数,并通过推理处理另一个参数。
function attachTheme<TTheme>() {
return function <TSelector>(config: IConfig<TTheme, TSelector>): OtherClass<TSelector> {
return null;
}
}
attachTheme<MyTheme>()({ select: theme => ({ background: theme.scroller.background }) });
我有这个方法:
attachTheme<TTheme, TSelector>(config: IConfig<TTheme, TSelector>): OtherClass<TSelector> {
}
IConfig:
interface IConfig<TTheme, TSelector> {
select(theme: TTheme): TSelector;
}
我想这样使用:
attachTheme<MyTheme>({ select: theme => ({ background: theme.scroller.background }) });
return 值是用 { background: string; }
键入的,但是如果我没有指定默认的 TSelector,它会抱怨,所以如果我把 {}
作为默认值,输出的通用类型是 {}
,尽管我觉得它应该推断类型。
我已经研究了 infer
关键字,但无法让它发挥作用,我觉得我对它的理解还不够深入,无法以正确的方式使用它,我希望有人会比我更好地理解它来解决我的问题吗?关于关键字的内容似乎很少,关于如何使用它的示例也更少。
最简单的解决方案是让编译器通过将主题指定为箭头函数参数的类型注释来推断这两个参数
attachTheme({ select: (theme: MyTheme) => ({ background: theme.scroller.background }) });
如果您不想在 3.1 中执行此操作,我们将得到 Named type arguments & partial type argument inference
另一种解决方案是使用返回函数的函数来指定一个参数,并通过推理处理另一个参数。
function attachTheme<TTheme>() {
return function <TSelector>(config: IConfig<TTheme, TSelector>): OtherClass<TSelector> {
return null;
}
}
attachTheme<MyTheme>()({ select: theme => ({ background: theme.scroller.background }) });