如何在 Typescript 函数接口中约束泛型类型? [英] How do you constrain a Generic type in a Typescript Function Interface?
问题描述
假设我们有以下接口:
interface SomeInterface {a: string; b: number}
interface SomeFunction<T> {(arg: T) :T}
我们可以像这样使用函数接口:
We can use the function interface like so:
const myFun: SomeFunction<string> = arg => arg;
但问题是我们将泛型类型 T
指定为字符串,因此它不再是泛型.我想保持类型 T
通用但也限制它.
but the issue with that is we specify the generic type T
as string, so it is no longer generic.
I would like to keep the type T
generic but also constrain it.
声明 SomeFunction
如:
interface SomeFunction {<T>(arg: T) : T}
允许它像一般使用:
const myFun: SomeFunction = (arg) => arg;
但是我们失去了在函数声明中约束 T
的机会.
but then we lose the chance to constrain T
at the function declaration.
我想要实现 SomeFunction
的函数来定义 T
必须扩展 SomeInterface
并且我想要另一个也实现 SomeFunction
来定义 T
扩展其他东西.
I would like my function that implements SomeFunction
to define that T
must extend SomeInterface
and I would like another function that also implements SomeFunction
to define that T
extends something else.
所以,基本上,我想要这样的东西:
So, basically, I want something like this:
function myFun2<T extends SomeInterface>(arg: T): T {
console.log(arg.a);
return arg;
}
function myFun3<T extends {c: string }>(arg: T): T {
console.log(arg.c);
return arg;
}
我在上述解决方案中遇到的问题是这些声明中没有提到 SomeFunction
接口,即使我们基本上匹配它.
The issue I have with the solution above is that there is no mention of the SomeFunction
interface in these declarations even though we basically match it.
是否有更好的方法来声明 myFun2
和 myFun3
以便我们确保它们符合 SomeFunction
?
Is there a better way to declare myFun2
and myFun3
so we make sure they conform to SomeFunction
?
推荐答案
如果您希望能够在调用站点定义约束,您可以使用约束类型来概括 SomeFunction
,例如
If you want the ability to define constraints at call site, you can generalise SomeFunction
with a constraint type, like
interface SomeFunction<C> {
<T extends C>(arg: T) : T
}
并在定义函数时提供正确的约束
and provide the correct constraint when defining your functions
const myFun2: SomeFunction<SomeInterface> = arg => {
console.log(arg.a) // ok
return arg
}
const myFun3: SomeFunction<{ c: string }> = arg => {
console.log(arg.c) // ok
return arg
}
如果你想允许不受约束的函数,你也可以给一个 unknown
类型的默认约束,比如
You could also give a default constraint of type unknown
if you wanted to allow unconstrained functions, like
interface SomeFunction<C = unknown> {
<T extends C>(arg: T): T
}
const unconstrained: SomeFunction = arg => arg
这篇关于如何在 Typescript 函数接口中约束泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!