Looking for guidance on converting JS code to TypeScript? Let's tackle this TS test together!

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!

Answer №1

Your existing bar function could use some simplification.

function bar<T extends keyof MyFoo>(methodName: T): MyFoo[T] {
  return myFoo[methodName];
}

Do you think it is sufficient, or do you believe further manipulation of the arguments is necessary in a real-world scenario?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to steer clear of using optional chaining in Typescript?

I'm currently working on storing object data known as Targetfarms in redux. I've defined a type named Farmstype for the Targetfarms. However, when I retrieve the Targetfarms using useSelector in the MainPage component and try to access targetfar ...

Issue with Loosing Focus in React TextInput when typing the letter "S"

My TextInput is acting strangely - it loses focus only when I type the letter s. All other letters work fine. <FormControl key={"1"} sx={{ m: 1 }} variant="outlined" onChange={handleFilterValueChange}> <InputLabel htmlFor=& ...

Troubleshooting a Jasmine Unit Testing Error for Button Click in Angular 4

Exploring the world of Jasmine and Angular 4, I am aiming to write tests for a button functionality in a multi file upload feature. Below is the code snippet from my spec file: import { async, ComponentFixture, TestBed } from '@angular/co ...

typescript add some flair to the setter function

I'm attempting to enhance a setter function within a class in the following manner: export class SearchResultSortBy{ private sortByChoice; constructor() { ...} /* getters & setters */ get sortBy() { return this.sortByCh ...

What are the best methods for implementing runtime type checking in JavaScript?

Utilizing either TypeScript or Facebook's Flow (type), I am empowered to statically assign types to variables like this: function add (x: integer, y: integer) { ... } Both TypeScript and Flow are able to identify and prevent incorrect invocations su ...

Encountering Invalid Chai attribute: 'calledWith'

I am currently in the process of implementing unit tests for my express application. However, I encountered an error when running the test: import * as timestamp from './timestamp' import chai, { expect } from 'chai' import sinonChai f ...

Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user ex ...

React typescript - Error: Type 'boolean' is not compatible with the expected type

Check out this demo This is a simple React application built with Typescript. Currently, I am experimenting with React's Context API. I have set up a context named ThemeContext which holds basic theme styling values to be used across different comp ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

The issue arises when Jest ceases to function properly once the "type": "module" is configured in the tsconfig.json file

I have encountered an issue while using jest for unit testing in typescript. When I set "type": "module" in the tsconfig.json file, my app runs perfectly fine but jest stops working and displays a "ReferenceError: require is not defined". const { pathsToMo ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Typescript is being lenient with incorrect use of generics, contrary to my expectations of error being thrown

Encountered a puzzling Typescript behavior that has left me confused. Take a look at the following code snippet: interface ComponentProps<T> { oldObject: T } function Component<T>({ oldObject }: ComponentProps<T>) { const newObject = ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Utilize a jest mock object and pass it as a method parameter to achieve seamless testing

I am attempting to create a mock object (ColumnApi from ag-grid) using jest and then pass it as a parameter to a function that calls the "getAllColumns" method from ColumnApi. I am not concerned with how the "getAllColumns" method functions, but I want it ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

What are the benefits of adding member functions to the data structures of React.js store?

Using React.js and Typescript, I store plain Javascript objects in the React.js store. These objects are sometimes received from the server without any member functions, but I wish to add functions for better organization. Instead of having to rely on exte ...

Eliminate repeat entries in MongoDB database

Within our MongoDB collection, we have identified duplicate revisions pertaining to the same transaction. Our goal is to clean up this collection by retaining only the most recent revision for each transaction. I have devised a script that successfully re ...

Troubleshooting: Imported Variable in Angular 2+ Throwing Module Not Found Error

During my testing process, I encountered an issue when trying to require a .json file with data to perform checks on. Despite passing the string indicating where to find the file into the require function, it seems to be unsuccessful... Success: const da ...

I'm in need of someone who can listen and detect any changes in my notifications table (node) in order to perform real-time data

Seeking a listener in Firebase to track changes in my notifications table for real-time data monitoring. My project is utilizing Angular 2 with TypeScript and Firebase. ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...