首页 > 解决方案 > 如何在 TypeScript 的通用类型参数中使用联合类型作为约束

问题描述

似乎不可能有一个受联合类型约束的泛型类。基本上是这样的:

class Shoe {
    constructor(public size: number){}
}

class Dress {
    constructor(public style: string){}
}

class Box <T extends Shoe | Dress > {
}

然后这个:

// because move can move multiple boxes of Box of shoes or Box of dress
class Move<B extends Box<Shoe>[] | Box<Dress>[]> {
    private stuff: B;
    constructor(public toMove: Box<Shoe>[] | Box<Dress>[]) {
        this.stuff = toMove // this does not compile
    }

}

或者如何实现?我有一个Playground 链接来展示这种情况

标签: typescriptgenericstypes

解决方案


我想,这又是对你真实意图的猜测,这应该足够了:

class Shoe {
    constructor(public size: number){}
}

class Dress {
    constructor(public style: string){}
}

class Box <T extends Shoe | Dress > {
}


// because move can move multiple boxes of Box of shoes or Box of dress
class Move<B extends Box<Shoe>[] | Box<Dress>[]> {
    private stuff: B;
    constructor(public toMove: B) {
        this.stuff = toMove;
    }

}

推荐阅读