我正在寻找一种方法来使我的代码更加类型安全,并希望在将它们传递给泛型函数时定义一些类型之间的密切关系。
例如,对于给定的类型集:
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)
我想紧密结合FooParam与FooReturn和BarParam用BarReturn的,所以编译器允许只有在对相关类型的作为通过调用T和R返回一个错误,否则。
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)