首页 > 解决方案 > 打字稿:如何从盒子的联合中提取类型?

问题描述

我有一些 Box 类型和 Union,其中包括装箱值和原始值。如何提取盒装类型?

class Box<T> {};
type United = Box<number> | Box<string> | boolean;
type Unboxed<T> = ???
type ExtractUnited = Unboxed<United>; // number | string

标签: typescripttypescript-generics

解决方案


首先,你必须T在你的Box类中使用:

class Box<T> {
    constructor(public value: T) {}
};

二、声明Unboxed<T>为:

type Unboxed<T> = T extends Box<infer U> ? U : never;

游乐场链接


推荐阅读