【发布时间】:2023-01-11 21:43:40
【问题描述】:
我需要将我所有的键和方法从对象联合到枚举
// i want that result [ 'aStore.aMethod1','aStore.aMethod2', 'bStore.bMethod1', 'bStore.bMethod2' ,''bStore.bMethod3'] sample
const objA = {
aMethod1: function (_params: string) {
console.log("obj A a method1")
return 'A1'
},
aMethod2: function (_params: string, _param2: string) {
console.log("obj A a method2")
return 'A2'
}
}
const objB = {
bMethod1: function (_params: string) {
console.log("obj b bmethod1")
return 'B1'
},
bMethod2: function (_params: string, _param2: string) {
console.log("obj B bmethod2")
return 'B2'
},
bMethod3: function (_params: string, _param2: string) {
console.log("obj B bmethod3")
return 'B3';
}
}
const rootStore = {
aStore: objA,
bStore: objB,
}
// https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html
type actionName<T> = `${string & keyof T}.${'HELP'}`;
/// how do i make typesafe here
// i want an action a list of [ 'aStore.aMethod1','aStore.aMethod2', 'bStore.bMethod1', 'bStore.bMethod2' ,''bStore.bMethod3']
// is there any way to make args type safe too.
function dynamicCall<T> (action: actionName<T>,...args:any) {
// it will call objA
const [storeName, method] = action.split('.');
const store= (rootStore as any)[storeName];
if(store&&store[method]){
(store as any)[method].apply(undefined,args)
}
}
dynamicCall<typeof rootStore>('aStore.aMethod1')
如果您也可以帮助使 args 类型安全,那将是完美的。 谢谢
【问题讨论】:
-
如果this 适合你,请告诉我
标签: typescript