【发布时间】:2021-10-02 01:58:58
【问题描述】:
我有以下功能:
export const createStore = <
OutputDocument extends Record<string, unknown>,
Actions extends Record<string, unknown>,
>(
inputDocument: Record<string, unknown>,
actions: () => Actions,
): OutputDocument & Actions => {
// this is actually a function that takes the input document and mutates it into `OutputDocument`
const outputDocument = inputDocument as unknown as OutputDocument
return Object.assign({}, outputDocument, actions())
}
我试图达到返回类型为强类型的地步。问题是我可以输入 OutputDocument 或输入 Actions,但不能同时输入。
如果我提供OutputDocument 类型(在我的实际应用程序中就是这种情况),那么Actions 就是Record<string, unknown>。
基本上我想要的是以下内容:
const test = createStore <{ output: string }>({ input: 'string here' }, () => ({ update: () => 'test' }))
我希望test 的类型为:
{ output: string } & { update: () => string }
我必须将输入变为输出的函数很难键入,这就是为什么我需要以某种方式为输出文档提供类型。
【问题讨论】:
-
那个实现是假的吗?因为仅仅将
inputDocument声明为OutputDocument并不会改变它的任何属性。 -
另外,你试图得到的东西目前是不可能的,因为你要么不指定任何泛型,要么必须指定所有。见this issue。
标签: typescript