【问题标题】:How to infer return type based on return type of function in parameters如何根据参数中函数的返回类型推断返回类型
【发布时间】:2021-10-02 00:37:56
【问题描述】:

我的应用中有以下功能:

const store = createStore(
  { value: false },
  (set, get) => ({
     changeValue: (newValue: boolean) => {
       set((state) => { state.value = newValue })
     }
  })
)

我正在尝试获取它,因此生成的 store 的类型是:

{ value: boolean, changeValue: (newValue: boolean) => void }

无需手动添加类型。我觉得应该有一种方法可以从该函数中 createStore 的 args 推断类型,但我无法弄清楚。

这是我的createStore 目前的样子:

export const createStore = <Document extends Record<string, unknown>>(
  document: Document,
  actions: () => Record<string, unknown>,
) => {
  return Object.assign({}, document, actions())
}

const test = createStuff({ hello: 'world' }, () => ({ update: () => 'test' }))

在这种情况下,test 的类型是

{
    hello: string;
} & Record<string, unknown>

我希望它是:

{
    hello: string;
} & { update: () => string }

【问题讨论】:

  • 这是来自 redux 的 createStore 吗?还是这是您自己创造的?
  • 这是定制的,我很确定内部不相关,但我想我可能错了。
  • 我的意思是你在谈论推断函数的返回类型`createStore, but you haven't shared that function with us, or what it actually returns. We need to see createStore` 以便能够提供帮助。
  • 好的,我添加了上面 createStore 的示例

标签: typescript


【解决方案1】:

您已经正确地利用Document extends Record&lt;string, unknown&gt; 创建了一个泛型,其中返回值包括您为第一个参数document 放置的任何参数。现在你只需要对actions 参数做同样的事情。它看起来像这样:

const createStore = <Document extends Record<string, unknown>, ActionReturn>(
    document: Document,
    actions: () => ActionReturn,
) => {
    return Object.assign(document, actions())
}

const test = createStore({ hello: 'world' }, () => ({ update: () => 'test' }))

现在test 的值输入为:

const test: {
    hello: string;
} & {
    update: () => "test";
}

Working codesandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-28
    • 2020-06-06
    • 2020-12-26
    • 2021-07-18
    • 1970-01-01
    • 2021-12-09
    • 2019-02-17
    相关资源
    最近更新 更多