我想写一个TypeScript接口,它是一个类型函数的泛型,而不仅仅是一个类型。
interface Foo<Functor> {
bar: Functor<string>;
baz: Functor<number>;
}
其中Functor
是我可以从外部传入的某个泛型类型别名。然后我就可以创建不同类型的Foo
,如下所示:
type Identity<T> = T;
type Maybe<T> = T | undefined;
type List<T> = T[];
// All of the following would typecheck
const fooIdentity: Foo<Identity> = { bar: "abc", baz: 42 };
const fooMaybe: Foo<Maybe> = { bar: undefined, baz: undefined };
const fooList: Foo<List> = { bar: ["abc", "def"], baz: [42, 43] };
我试图找到一种方法来让编译器接受这一点,但没有运气,所以我想知道是否有一个技巧,我错过了或如果TypeScript只是不能表达这一点。
1条答案
按热度按时间xj3cbfub1#
我迟到了,但现在有一个全面的解决方案,这个问题的用户端,所以我想我可能会分享它。
关于它如何工作的细节可以在here中找到,但简单地说,我们利用了接口可以通过交集接收参数的事实:
运动场
请注意我们是如何将类型构造函数与其值分离的。
这种模式非常灵活,并支持创建free-types库,该库添加了一系列特性,如支持类型约束、部分应用、组合、可变性、可选性、推理等。
那么,我们可以如何处理您的使用情形呢?
从技术上讲,
List
和Identity
有现成的类型,我们只需要定义$Maybe
即可,也可以将Identity
作为Foo
的默认参数,这样比较方便。您可能需要检查您的类型构造函数是否实际上可以接受
string | number
。您可能还需要检查您的类型是否实际上是一个Functor(这里只针对
List
)。最后,如果你不喜欢有两个版本的相同类型,你可以合并成一个。
运动场