【发布时间】:2019-09-11 09:50:54
【问题描述】:
我有 2 个版本的数据模型(称为 A 和 B),我希望能够在这些实例上执行函数,无论它们是 A 还是 B。函数本身特定于A 型和 B 型。
我想出了解决此问题的方法,但它们都涉及声明一个泛型类型(即Functions<T>),而我目前的设置无法轻松做到这一点。
type A = {
a: string;
}
type B = {
b: string;
}
type AFunctions = {
make: () => A;
do: (obj: A) => void;
}
type BFunctions = {
make: () => B;
do: (obj: B) => void;
}
type Bundle<
Fns extends AFunctions | BFunctions,
T extends ReturnType<Fns['make']> = ReturnType<Fns['make']>
> = {
obj: T,
fns: Fns,
}
function doIt<M extends AFunctions | BFunctions>(bundle: Bundle<M>) {
bundle.fns.do(bundle.obj);
}
在bundle.fns.do(bundle.obj); 行,我得到一个打字稿错误:Argument of type 'ReturnType<M["make"]>' is not assignable to parameter of type 'A & B'
我希望doIt 是类型安全的,因为bundle.obj 与bundle.fns.do 上的参数类型相同。怎么了,这里?有没有办法在不引入通用Functions<T> 的情况下解决这个问题?
我也可以将{ type: 'a' }和{ type: 'b' }参数分别添加到Bundles,然后检查:
if (bundle.type === 'a') {
bundle.fns.do(bundle.obj);
} else if (bundle.type === 'b') {
bundle.fns.do(bundle.obj);
}
但这种冗余并不理想。
我认为这与缩小泛型类型的问题有关:https://github.com/microsoft/TypeScript/issues/17859
【问题讨论】:
标签: typescript typescript-generics