能正常推导的例子
function createStore<R, E extends Record<string, (arg: R) => void>>(reducers: R, effects: E) {}
createStore(
{
hello() {},
},
{
world(arg) {
// 这里能自动推导 arg: { hello(): void }
arg.hello();
},
},
);
我封装库需要写成以下参数形式
function createStore<
R,
E extends Record<string, (arg: R) => void>
>(store: { reducers: R; effects: E }) {}
createStore({
reducers: {
hello() {},
},
effects: {
world(arg) {
// 这里无法推导 TS2571: Object is of type 'unknown'.
arg.hello();
},
},
});
有没有办法让下面这种 store 对象参数形式也支持类型自动推导?
1
youmoo 2021-04-16 17:38:02 +08:00
后一个 createStore 之所以报错,是因为它无法推导出 R 的实际类型,我发现这样调用就行了:
```js createStore({ reducers: { hello() { }, } as const, effects: { world(arg) { arg.hello(); }, }, }); ``` https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABBATgUwIZTQZSndAHgChFEAlAGlMQFFE0APbMAEwGcK0IDXD2oKGGADmlRAAoMKEQC4KASkQBeAHyIAbnBitVxVRIEE08gN6J0rEBDQp288gG4GwYNyj26iAL5Lz34kDUTGw8YwlTGktrW09IsjIACzQAGxS4CT8fajJvRAxOHjABHJc3aDiaMgB3AhTWKRk-KoTpEQA6ZLSMhUcW71KB4l8+oA |