I am facing the challenge of encapsulating a very complex SDK into a layer of code. I have attempted to utilize union and index types for this task, and below is a demo that I have created. How can I implement the bar method in TypeScript to pass the console test successfully?
JavaScript code:
class Foo {
add (a, b) {
return a + b
}
isZero (num) {
return num === 0
}
free (...args) {
return args.join('-')
}
}
const foo = new Foo()
function bar(funcName) {
return (...args) => {
return foo[funcName](...args)
}
}
console.log( bar('add')('1', '2') ) // 12
console.log( bar('isZero')(10) ) // false
console.log( bar('free')('a', 1, '2', 'c', 'd') ) // a-1-2-c-d
TypeScript code:
class Foo {
add (a: string, b: string): string {
return a + b
}
isZero (num: number): boolean {
return num === 0
}
free (...params: any[]): string {
return params.join('-')
}
}
const foo = new Foo()
function bar(funcName: keyof Foo) {
// Implementation code needed here
}
console.log( bar('add')('1', '2') )
console.log( bar('isZero')(10) )
console.log( bar('free')('a', 1, '2', 'c', 'd') )
Any suggestions are greatly appreciated!