【发布时间】:2019-10-13 20:28:35
【问题描述】:
我的一个通用函数中的可分配值有问题:
interface BuildArguments<T extends string> {
type: T;
}
type PromiseResult<T> =
T extends 'standalone' ? Promise<void> :
T extends 'all' ? Promise<void> :
Promise<void[]>;
const foo: PromiseResult<'standalone'> = Promise.resolve();
const bar: PromiseResult<'all'> = Promise.resolve();
const baz: PromiseResult<'foo'> = Promise.resolve([]);
bundle({ type: 'foo' });
function bundle<T extends string>(buildArguments: BuildArguments<T>): PromiseResult<T> {
switch (buildArguments.type) {
case 'standalone':
return Promise.resolve(); // error here, not assignable to PromiseResult<T>
case 'all':
return Promise.resolve(); // error here, not assignable to PromiseResult<T>
default:
return Promise.all([ // error here, not assignable to PromiseResult<T>
Promise.resolve(),
Promise.resolve()
]);
}
}
consts foo、bar 和 baz 表明条件类型工作正常。如果您使用 ts 操场并将鼠标悬停在其上,则函数调用 bundle({ type: 'foo' }) 也正确提供了类型 Promise<void[]>。为什么它不适用于返回值?
如果这是由于 TypeScript 无法通过向函数添加 kind: T 参数来推断 T 引起的,我也尝试过,但没有任何更改。断言 Promise.resolve() 到 PromiseResult<T> 工作正常。
【问题讨论】:
标签: typescript