I want to unwrap some types in TypeScript, here is example:
// 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
.
.
.
How Unwrap can be defined?
You can use mapped and conditional types and mapped types to unwrap the type:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.