简体   繁体   English

Typescript:创建通用展开<t>辅助类型</t>

[英]Typescript: create generic Unwrap<T> helper type

I've created a helper type to unwrap the inner type of an Observable<T> :我创建了一个辅助类型来解开Observable<T>的内部类型:

type UnwrapObservable<T> = T extends Observable<(infer U)> ? U : never;

This works just fine.这工作得很好。 But... my next thought was, "How can I make this type completely generic and apply to any type, not just Observable, essentially Unwrap<T> ?但是......我的下一个想法是,“我怎样才能使这种类型完全通用并适用于任何类型,而不仅仅是 Observable,本质上是Unwrap<T>

Here's what I tried:这是我尝试过的:

type Unwrap<T, W> = T extends W<(infer U)> ? U : never;

But I get:但我得到:

Type 'W' is not generic.类型“W”不是通用的。 ts(2315) ts(2315)

How can I create a type that unwraps any specified type?如何创建一个可以解开任何指定类型的类型?

What You are trying to do is impossible in TS, but as far as I know it is possible in Flow)您尝试做的事情在 TS 中是不可能的,但据我所知,在 Flow 中是可能的)

In TS you can't apply restrictions for generic which expects other generic as argument.在 TS 中,您不能对期望其他泛型作为参数的泛型应用限制。

This is the most generic Wrap type这是最通用的Wrap类型

type Wrapp<T> = { wrapped: T }
type Unwrap<T> = T extends Wrapp<(infer R)> ? R : never

Please see here for similar limitation请参阅此处了解类似的限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM