小编jsa*_*mol的帖子

如何在 TypeScript 中使一种泛型类型紧密依赖于另一种类型?

我正在寻找一种方法来使我的代码更加类型安全,并希望在将它们传递给泛型函数时定义一些类型之间的密切关系。

例如,对于给定的类型集:

interface FooParam {}
interface FooReturn {}

interface BarParam {}
interface BarReturn {}
Run Code Online (Sandbox Code Playgroud)

以及以下功能:

function action<T, R>(foo: T): R
Run Code Online (Sandbox Code Playgroud)

我想紧密结合FooParamFooReturnBarParamBarReturn的,所以编译器允许只有在对相关类型的作为通过调用TR返回一个错误,否则。

action<FooParam, FooReturn>(...) // bound types, OK
action<BarParam, BarReturn>(...) // bound types, OK

action<FooParam, BarReturn>(...) // types are not bound, ERROR
action<FooParam, string>(...) // types are not bound, ERROR
Run Code Online (Sandbox Code Playgroud)

我实际上已经通过定义两个基本接口来实现上述目标,这些接口稍后将用作泛型类型的约束:

interface Param {}
interface Return<T extends Param>{
    _typeGuard?: keyof T
}

interface FooParam extends Param {}
interface FooReturn …
Run Code Online (Sandbox Code Playgroud)

generics typescript

7
推荐指数
1
解决办法
761
查看次数

标签 统计

generics ×1

typescript ×1