【发布时间】:2020-03-24 16:00:10
【问题描述】:
这样的代码:
const t = {
k1: null,
k2: null,
}
const a = {
k1: () => null,
k2: (arg1: number) => null,
}
a.k1()
a.k2()
现在我想对象“a”将由对象“t”中的键控制,我想当我写k3,k4时,“t”上不存在哪个键,到“a”,应该有一个错误
所以我试试这个方法
const t = {
k1: null,
k2: null,
}
const a: Record<keyof typeof t, (...args: any[]) => void> = {
k1: () => null,
k2: (arg1: number) => null,
}
a.k1()
a.k2()
但是当我调用a.k2时,args没有提示,即使我不输入参数也没有编译器错误。
所以,我写下我的想法:
const t = {
k1: null,
k2: null,
}
const a: Record<keyof typeof t, (...args: Parameters<typeof a[keyof typeof t]>) => null> = {
k1: () => null,
k2: (arg1: number) => null,
}
a.k1()
a.k2()
但是,编译器出错:
'args' 在它自己的类型注解中被直接或间接引用。
我最后想要的是:
const t = {
k1: null,
k2: null,
}
const a: ????? = {
k1: () => null,
k2: (arg1: number) => null,
k3: ()=>null, // should have an error like, 'k3' does not exist in keyof typeof t
}
a.k1()
a.k2() // should have an error like, An argument for 'arg1' was not provided.
我不知道类型“??????”应该换成什么。
我可以为“key contorll && arguments Tips”做些什么?或者我怎样才能只指定函数的返回类型而不指定参数?
【问题讨论】:
标签: typescript generics typescript-typings typescript-generics