【发布时间】:2018-05-28 21:39:32
【问题描述】:
我正在尝试使 typescript 打字与一个模式一起工作,其中有一个 object 函数和一个函数 call(name, arg),它在 object 中查找函数通过name 并使用arg 调用它。
假设我有一个将名称映射到函数的对象:
interface Registry {
str2numb: (p: string) => number
num2bool: (p: number) => boolean
}
const REGISTRY: Registry = {
str2numb: p => parseInt(p, 10),
num2bool: p => !!p,
}
我还有一个函数call(name, p),它从REGISTRY 解析函数并用p 调用它。现在,我想输入这样的函数,如果提供了无效的参数,它会抱怨:
const call = (name, p) => REGISTRY[name](p)
call('str2numb', 123)
// ^^^ Would like to see an error here
如何从Registry.str2numb 的类型中解析参数p 的类型P(以及返回类型R)?有没有可能?
// How can I resolve P and R here?
// The resolved function is Registry[N]
// I have tried Registry[N]<P, R> but that doesn't work :-(
const call = <N extends keyof Registry>(name: N, p: P): R => REGISTRY[name](p)
我已经做到了这一点,但它不起作用:
type Fn<P, R> = (p: P) => R
const call =
<N extends keyof Funcs, F extends Funcs[N] & Fn<P, R>, P, R>
(name: N, p: P): R =>
REGISTRY[name](p)
call('str2numb', 123)
// ^^^ No error here
但是这可行:
// This just returns the resolved function
const call1 = <N extends keyof Funcs>(name: N) => REGISTRY[name]
// The type of the returned function is correctly inferred from the name
call1('str2numb')(123)
// ^^^ Argument of type '123' is not assignable to parameter of type 'string'
【问题讨论】:
标签: typescript type-inference typescript-generics