假设我想要在单个函数中管理来自项目中不同模块的服务,根据我获得的数据类型,我调用不同的服务.
例如,我有两个DTO:
class UserDto {
constructor (name: string) {
this.name = name
}
public name: string;
}
class CarDto {
constructor (brand: string) {
this.brand = brand
}
public brand: string;
}
和这两项服务:
class UserService {
create(val: UserDto) {
// Create the user
return 'foo';
}
}
class CarService {
create(val: CarDto) {
// Create the car
return 'bar';
}
}
很基本的东西.然后,我可以获得一个服务,该服务可以根据我获得的数据类型来管理呼叫.为此,我创建了一个联合类型,该类型应该计算出我要获取的数据类型以及我应该调用什么服务,假设是这样的:
type DataType =
| {
data: 'user';
dto: UserDto;
service: 'userService'
}
| {
data: 'car';
dto: CarDto;
service: 'carService'
}
最后,我想将所有这些放在管理这两个子服务的服务中的一个函数中,如下所示:
class MainService {
constructor (
private userService: UserService,
private carService: CarService,
) {}
serviceManager(val: DataType) {
// Call the right service here!
}
}
我不想做的是判断每一处房产,如果那是我想要的.This is what I'd like to avoid:
serviceManager(val: DataType) {
const name = val.data;
if (name === 'user') this.userService.create(val.dto);
}
相反,我更喜欢这样一种方法,即通过打字来推断我得到了什么服务,以及我正在向所述服务传递什么信息.因此,这就是I thought应该起作用的地方(剧透,它没有):
serviceManager(val: DataType) {
const func = this[val.service];
func.create(val.dto);
// Argument of type 'UserDto | CarDto' is not assignable to parameter of type 'UserDto & CarDto'.
// Type 'UserDto' is not assignable to type 'UserDto & CarDto'.
// Property 'brand' is missing in type 'UserDto' but required in type 'CarDto'.
}
最后,我决定走另一条路,甚至不使用子服务.但我一直在试图找到解决这个问题的方法,即使它与我正在工作的项目无关.
是否有可能通过某种不同的方式声明类型dataType来使用TypeScrip实现类似的操作,或者这完全是不可能的?也许我应该在声明子服务中的函数时使用泛型?