[英]Nested Typescript Generics
我有以下课程:
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;
}
虽然多键入两个类型参数的解决方案也不错,但如果U
与布局所期望的T
不兼容,并且正确指定了类型约束,则会给您带来适当的错误:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.