如何解决在TypeScript中递归地解开对象类型
我想在TypeScript中解开某些类型,这是示例:
// previously defined Type<T>
// example of wrapped type:
type Wrapped = Type<{
a: Type<boolean>,b: Type<{
c: Type<number>
}>
}>
type Unwrap = ...// this needs to be defined
//And its usage like:
type Unwrapped1 = Unwrap<Wrapped>// should be: { a: boolean,b: { c: number } }
type Unwrapped2 = Unwrap<Type<string>>// should be: string
.
.
.
如何定义展开?
解决方法
您可以使用映射和条件类型以及映射类型来解开类型:
type UnwrapObject<T> = {
[P in keyof T] : Unwrap<T[P]>
}
type Unwrap<T> = T extends Type<infer U> ?
U extends object ? UnwrapObject<U> : U:
T extends object ? UnwrapObject<T> : T
//And its usage like:
type Unwrapped1 = Unwrap<Wrapped>// should be: { a: boolean,b: { c: number } }
type Unwrapped2 = Unwrap<Type<string>>// should be: string
declare let d: Unwrapped1;
d.b.c // number
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。