【问题标题】:specify a generic and infer a generic in the same typescript function在同一个打字稿函数中指定泛型并推断泛型
【发布时间】: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&lt;string, unknown&gt;

基本上我想要的是以下内容:

const test = createStore <{ output: string }>({ input: 'string here' }, () => ({ update: () => 'test' }))

我希望test 的类型为:

{ output: string } & { update: () => string }

我必须将输入变为输出的函数很难键入,这就是为什么我需要以某种方式为输出文档提供类型。

【问题讨论】:

  • 那个实现是假的吗?因为仅仅将inputDocument 声明为OutputDocument 并不会改变它的任何属性。
  • 另外,你试图得到的东西目前是不可能的,因为你要么不指定任何泛型,要么必须指定所有。见this issue

标签: typescript


【解决方案1】:

函数签名按原样工作,但您必须显式设置所有泛型,因为编译器无法推断返回类型和 language limitation

const test = createStore<{ output: string }, { update: () => string }>(
  { input: 'string here' },
  () => ({ update: () => 'test' }),
);

请注意,实现不会满足函数声明的内容,这仍然会返回一个运行时类型为的对象

{ input: string, update: () => string }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2021-03-10
    • 2020-06-08
    • 2020-03-22
    • 2021-09-29
    • 2020-12-17
    相关资源
    最近更新 更多