如何在返回的函数记录中保留函数参数类型
How do I retain function parameter types in a returned Record of functions
我有一个简单的函数,它将一个函数对象作为参数,returns那个对象。
type Func = () => void
type Async = () => Promise<void>
const foo = <K extends string>(fns: Record<K, Func | Async) => fns
理想情况下,每个函数都应该能够接受参数,并在从函数返回时在对象中保留参数的类型签名。像这样:
const fns = foo({
foo: (a: string, b: string) => {}
asyncFoo: async (a: string, b: string) => {}
})
// typescript doesn't know that a, b are parameters
// will complain that I am passing these parameters
// since they don't exist in the type signature
fns.foo('a', 'b')
await fns.asyncFoo('a', 'b')
如何键入此函数,以便从它返回的函数对象可以 infer/retain 参数类型?
旁注:实际代码的灵感来自 @redux-toolkit
,这种行为的一个很好的例子是 createSlice()
以及操作如何保留传递给函数。
发帖后我找到了答案哈哈
基本上我需要添加这个类型:
type Func = (...args: any[]) => void
type AsyncFunc = (...args: any[]) => Promise<void>
const foo = <K extends Record<keyof K, Func | AsyncFunc>>(fns: K) => fns
我有一个简单的函数,它将一个函数对象作为参数,returns那个对象。
type Func = () => void
type Async = () => Promise<void>
const foo = <K extends string>(fns: Record<K, Func | Async) => fns
理想情况下,每个函数都应该能够接受参数,并在从函数返回时在对象中保留参数的类型签名。像这样:
const fns = foo({
foo: (a: string, b: string) => {}
asyncFoo: async (a: string, b: string) => {}
})
// typescript doesn't know that a, b are parameters
// will complain that I am passing these parameters
// since they don't exist in the type signature
fns.foo('a', 'b')
await fns.asyncFoo('a', 'b')
如何键入此函数,以便从它返回的函数对象可以 infer/retain 参数类型?
旁注:实际代码的灵感来自 @redux-toolkit
,这种行为的一个很好的例子是 createSlice()
以及操作如何保留传递给函数。
发帖后我找到了答案
基本上我需要添加这个类型:
type Func = (...args: any[]) => void
type AsyncFunc = (...args: any[]) => Promise<void>
const foo = <K extends Record<keyof K, Func | AsyncFunc>>(fns: K) => fns