作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想实现的最好用代码来解释:
给定鞋类和服装类:
class Shoe {
constructor(public size: number){}
}
class Dress {
constructor(public style: string){}
}
class Box <T extends Shoe | Dress > {
}
class ShoeMover {
constructor(public size: number[]){}
}
class DressPacker {
constructor(public style: string[]){}
}
Box<Shoe>
实例化或
Box<Dress>
有一个
mover
使用
ShoeMover
的方法或
DressPacker
:
class Move<B extends Box<Shoe> | Box<Dress>> {
private box: B;
constructor(toMove: B) {
this.box = toMove;
}
public mover(tool: ShoeMover | DressPacker) {
}
}
Move
用
Box<Shoe>
实例化,然后是
mover
方法应该只接受
ShoeMover
.如果用
Box<Dress>
实例化.
mover
方法应该只接受
DressPacker
.那是:
let shoemover = new Move(new Box<Shoe>());
// compile
shoemover.mover(new ShoeMover([21]))
// should not compile. But currently does
shoemover.mover(new DressPacker(["1"]))
type MoverFromEitherShoeOrDressA<T> =
T extends Box<infer U> ?
U extends Shoe ? ShoeMover :
U extends Dress ? DressPacker :
never:
never;
and
type MoverFromEitherShoeOrDressB<T> =
T extends Box<Shoe> ? ShoeMover:
T extends Box<Dress> ? DressPacker:
never;
mover
的定义从:
public mover(tool: ShoeMover | DressPacker) {
}
public mover(tool: MoverFromEitherShoeOrDressB) {
}
or
public mover(tool: MoverFromEitherShoeOrDressA) {
}
Move
的构造函数时更改为采用联合类型。
type Mover<T> =
T extends Shoe ? ShoeMover :
T extends Dress ? DressPacker :
never;
class Move<T extends Shoe | Dress> {
private box: Box<T>;
constructor(public toMove: Box<Shoe>[] | Box<Dress>[]) {
this.box = toMove;
}
public mover(tool: Mover<T>) {
}
}
let shoemover = new Move(new Array<Box<Shoe>>());
// compile
shoemover.mover(new ShoeMover([21]))
// should not compile. But currently does
shoemover.mover(new DressPacker(["1"]))
最佳答案
你快到了,你只需要在 mover
中使用泛型方法也一样,否则它不知道是什么T
伊斯兰国。将泛型类型视为以泛型 T 作为参数的方法,以及 <>
如 ()
:
type Mover<T> =
T extends Shoe ? ShoeMover :
T extends Dress ? DressPacker :
never;
class Move<T extends Shoe | Dress> {
private box: Box<T>;
constructor(toMove: Box<T>) {
this.box = toMove;
}
public mover(tool: Mover<T>) {
}
}
Move
定义排除
Box
泛型,因为您可以轻松地将其封装在类内部定义中,但您的解决方案也适用于:
type MoverFromEitherShoeOrDressA<T> =
T extends Box<infer U> ?
U extends Shoe ? ShoeMover :
U extends Dress ? DressPacker :
never:
never;
public mover(tool: MoverFromEitherShoeOrDressA<B>) { // <-- Here
}
关于typescript - TypeScript 中带有泛型的条件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61541059/
我是一名优秀的程序员,十分优秀!