我有以下课程:
class Walls { }
class Furniture { }
class Layout<T extends Walls | Furniture> { }
class Space extends Layout<Walls> { }
class Room extends Layout<Furniture> { }
我需要创建这两个类:
class SpaceController extends LayoutController<Space> { }
class RoomController extends LayoutController<Room> {}
要做到这一点,我不能创建LayoutController
这样的类:
class LayoutController<T extends Layout>{ }
因为Layout
需要一个Type参数。
我可以改成这个:
class LayoutController<U, T extends Layout<U extends Walls | Furniture>>{ }
但这意味着我将必须这样做:
class SpaceController extends LayoutController<Walls, Space> { }
class RoomController extends LayoutController<Furniture, Room> {}
我觉得这是多余的。而且,它为错误提供了空间。没有什么可以阻止我写作:
class RoomController extends LayoutController<Walls, Room> {}
我该如何解决?
有关LayoutController
的更多详细信息:
class LayoutController<T> extends React.Component<{}, LayoutControllerState<T>>() { }
interface LayoutControllerState<T> {
selectedLayout: T;
}
答案 0 :(得分:2)
虽然多键入两个类型参数的解决方案还不错,但如果U
与布局所期望的T
不兼容,并且正确指定了类型约束,则会给您适当的错误:< / p>
class Walls { height!: number; }
class Furniture { price!: number; }
class Layout<T extends Walls | Furniture> { children: T[] = []; }
class Space extends Layout<Walls> { private x: undefined; }
class Room extends Layout<Furniture> { private x: undefined; }
class LayoutController<U extends Walls | Furniture, T extends Layout<U>>{
getValue(u: U) : void{}
}
class SpaceController extends LayoutController<Walls, Space> { }
class RoomController extends LayoutController<Furniture, Room> {}
class ErrController extends LayoutController<Walls, Room> {} //Type 'Room' does not satisfy the constraint 'Layout<Walls>
我们可以使用条件类型从Layout
类型中提取泛型参数,并将其作为U
的默认值。因此,我们不必指定冗余参数:
type ExtractLayoutParameter<T extends Layout<any>> = T extends Layout<infer U> ? U: never;
class LayoutController<T extends Layout<any>, U extends Walls | Furniture= ExtractLayoutParameter<T>>{
getValue(u: U) : void{}
}
class SpaceController extends LayoutController<Space> { }
class RoomController extends LayoutController<Room> {}
new SpaceController().getValue(new Walls())
new SpaceController().getValue(new Furniture()) // error
我们也可以使用条件类型而不是U
,从而不允许用户将U
更改为布局所接受的派生类型(取决于您的用例的功能或设计)您决定的限制):
type ExtractLayoutParameter<T extends Layout<any>> = T extends Layout<infer U> ? U: never;
class LayoutController<T extends Layout<any>>{
getValue(u: ExtractLayoutParameter<T>) : void{}
}
class SpaceController extends LayoutController<Space> { }
class RoomController extends LayoutController<Room> {}
new SpaceController().getValue(new Walls())
new SpaceController().getValue(new Furniture()) // error