【发布时间】:2021-12-06 11:18:40
【问题描述】:
如果不举个例子,这个问题有点难以解释,所以让我们看看这个Message 类型,它将被扩展并用作其他类型的基类型。
interface Message<E extends string = string, P = any> {
topic: E;
params: P;
}
我有这个接口用于指示消息类型。主题和参数是通用的,以确保接口可以针对不同的情况进行扩展,例如:
interface OrderParams {
userId: string;
orderId: string;
}
interface CreateOrderMessage extends Message<'orders.create', OrderParams> {}
interface UpdateOrderMessage extends Message<'orders.update', OrderParams> {}
...
type CustomMessage = CreateOrderMessage | UpdateOrderMessage | ...;
这让我可以为 topic 和 params 添加严格的类型,以便我可以在一个类中使用这些不同的主题类型:
class PubSub<T extends Message = Message> {
publish(message: T): void;
subscribe(topic: string): void;
}
如果我们将CustomMessage 作为泛型类型传递给PubSub<>,它将检查publish 方法的类型,但我还想确保subscribe 方法的topic 参数也使用@987654332 进行类型检查@泛型类型的T extends Message泛型类型。
那么,有没有办法以某种方式提取另一个泛型类型的泛型类型,以便我可以编写如下内容?
subscribe(topic: GenericOf<T, 0>); // 1st generic of T type
subscribe(topic: TypeOfObjectKey<T, 'topic'>); // Type of 'topic' property of T type
【问题讨论】:
-
subscribe(topic: T['topic'])做你想做的事吗?我认为这至少涵盖了您的第二个示例(TypeOfObjectKey<T, 'topic'>)。不确定您要对第一个 (GenericOf<T, 0>) 做什么。 -
@Wing 没有尝试或意识到这一点,谢谢!您可以将其发布为答案
-
"不确定你想用第一个 (GenericOf
) 做什么" - 正如我所说我不知道 T[key] 所以我发布了 2示例是否可以获得泛型类型或属性类型。 -
啊,好吧,我没有完全理解您的问题,并认为您可能正在尝试诸如在联合中获得第一种类型或类似的东西。感谢您的确认:)
标签: typescript typescript-generics