Ways to eliminate type errors when coding in TypeScript and prevent them from occurring in the following code

const obj = {
  extend: (p: {
    property: string;
    methods: { name: string; call: string; params: number }[];
  }) => {
    obj[p.property] = {};
    p.methods.forEach((m) => {
      obj[p.property][m.name] = (params: any[]) =>
        m.call + "____" + params.length;
    });
  },
};

obj.extend({
  property: "Scope1",
  methods: [
    {
      name: "functionName",
      call: "function_name",
      params: 1,
    },
  ],
});
// Ways to prevent type errors from occurring in TypeScript. The code below may prompt type errors due to missing types.
console.log(obj["Scope1"].functionName(["firstParam"]));

The method to avoid type errors in the TypeScript implementation of obj extend is by ensuring proper typing for all properties and methods.

Answer №1

Your requirement for how the extend() function works is quite generic.

To ensure type safety and generic functionality, we can introduce an ObjectTemplate that satisfies the Typescript compiler. This way, we can dynamically assign values to objects in TypeScript.

type Args = {
    property: string;
    methods: { name: string; callFunc: string; numParams: number }[];
}

type ObjTemplate = {
  extend: (args: Args) => void;
  [k: string]: any
}

const obj: ObjTemplate = {
  extend: (p: Args) => {
    obj[p.property] = {};
    p.methods.forEach((m) => {
      obj[p.property][m.name] = (params: any[]) =>
        m.callFunc + "____" + params.length;
    });
  }
};

obj.extend({
  property: "Scope1",
  methods: [
    {
      name: "functionName",
      callFunc: "function_name",
      numParams: 1,
    },
  ],
});

console.log(obj["Scope1"].functionName(["firstParam"]));

Code Playground

Answer №2

After reading through a discussion on typescript-interface-problem, I came across a solution that caught my attention.


export const customObject = {
  extend: <T extends string, O extends string>(data: {
    property: T;
    methods: { name: O; call: string; params: number }[];
  }): {
    [Prop in typeof data as Prop["property"]]: {
      [Prop in typeof data.methods[number] as Prop["name"]]: (
        ...args: any
      ) => Promise<any>;
    };
  } => {
    const obj = {} as any;
    data.methods.forEach((method) => {
      obj[method.name] = (...args: any) => {
        return Promise.resolve("success");
      };
    });

    const newObject = {
      [data.property]: obj,
    };

    return newObject;
  },
};

const extendedCustomObj = customObject.extend({
  property: "Scope1",
  methods: [
    {
      name: "functionName",
      call: "function_name",
      params: 1,
    },
  ],
});

Following the implementation of the above code snippet, we can observe the desired outcome.

https://i.sstatic.net/79YOU.png

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

What is the process of determining if two tuples are equal in Typescript?

When comparing two tuples with equal values, it may be surprising to find that the result is false. Here's an example: ➜ algo-ts git:(master) ✗ ts-node > const expected: [number, number] = [4, 4]; undefined > const actual: [number, number] ...

Utilizing multiple page objects within a single method in Cypress JS

I have been grappling with the concept of utilizing multiple page objects within a single method. I haven't been able to come up with a suitable approach for implementing this logic. For instance, consider the following methods in my page object named ...

How can you restrict a textbox input to accept only numerical values and decimals using ng-pattern?

I'm working on a code that needs to accept both decimals and integers. How can I verify this using the ng-pattern? An example of the code: Some test cases include: 1) 22 = Should pass, 2) 22.5 = Should pass, 3) 2a = Should fail, 4) @#@ = Should ...

What is causing an empty box to appear due to padding? Is there a way to conceal it

There seems to be an issue with adding padding to the results id div box. The padding is causing a blank yellow box to appear at the bottom before any results are submitted. I've tried to hide this box without success by adding a displayResult() funct ...

Updating a div using PHP elements

Currently, I'm using a webcam to capture images for a project related to learning. My goal is to showcase the recently taken photos. After taking a photo, it gets stored in a folder. To display all the collected photos within a <div>, I need to ...

Document.querySelector failing to execute the if statement properly

Currently, I am working on implementing a hamburger menu functionality. The basic setup involves creating a menu that transforms into a cross icon when clicked, and this part is functioning correctly. function drop(){ let bars = document.querySelector(" ...

Incorporating a stylish background image into an EJS template

I'm able to successfully display an image from my app.js file in the main ejs file, but when I try to set it as a background image, it doesn't show up. Any thoughts on what might be causing this issue? This is my app.js file: const express = re ...

Utilizing a default value for undefined object property in VueJS interpolation

Is there a way to handle undefined object property values in VueJS interpolation by setting a default value? I am working with a computed variable called data that is initially undefined until a selectedDataId is chosen from a selectbox. As a result, Vue t ...

What is the best way to set up TSLint to apply specific rules with one line and different rules with another line

There is a unique method in which I can specify the code to format, such as forcing the else statement to be on the same line as the ending brace of an if statement. "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-fin ...

What is the reason for Jest attempting to resolve all components in my index.ts file?

Having a bit of trouble while using Jest (with Enzyme) to test my Typescript-React project due to an issue with an alias module. The module is being found correctly, but I believe the problem may lie in the structure of one of my files. In my jest.config ...

Using the power of underscore.js, effortlessly uncover the desired string within an array of objects

How can I use underscore.js to search for a specific String inside an object? Here is the JSON data: { data: [ {'id': 1, 'name': 'New Samsung Galaxy 3' }, {'id': 2, 'name': &apos ...

The carousel's slides don't behave properly when swiping or using the slider controls (next/prev)

I have recently completed the construction of a carousel with swipe/touch functionality and control buttons for previous and next slides. However, I am facing an issue with the behavior of the carousel as it seems to be sliding by 2 or 3 instead of one at ...

Creating an input in Vue3/Javascript that restricts input to only numbers seems to be a challenge

I have a project that involves an input field which should only accept numerical values. Within the template, I've set up an input element with the value bound to a variable and the input event linked to a function that verifies if the entered value ...

What is the distinction between using localStorage and storing individual files when clicking?

Recently, I created a basic jQuery script that stores values such as "voted1", "voted2", and "voted3" in localStorage. However, I encountered an issue where all values are stored simultaneously on click, whereas I require them to be stored individually per ...

Create a collection of functions within an array that each return promises

I have created 4 different functions that return promises. By running the "hello" function and passing each subsequent function into the next .then, you can generate a single long string output. var hello = function(str){ return Promise.resolve(str + "h ...

Can $event be transferred from cshtml to Vue.component?

I am facing an issue when trying to pass an event into my Vue component. No matter what method I try, I keep getting a "TypeError: Cannot read property 'preventDefault' of undefined" error. Here is the code snippet for my Vue component: Vue.com ...

Typescript struggling to load the hefty json file

Currently, I am attempting to load a JSON file within my program. Here's the code snippet that I have used: seed.d.ts: declare module "*.json" { const value: any; export default value; } dataset.ts: import * as data from "./my.json" ...

Instructions on how to send HTML content as a string to a different function for iteration?

Encountering an issue where a function is returning JSON data upon success. Attempting to implement infinite scroll functionality, the function prepares HTML for looping in another function. The server response includes JSON structured as follows: { "id" ...

Create a customized multibar chart in Angular using NVD3 that displays only a line graph on the dual y-axis, visualizing

Currently, I am experimenting with developing an angular multibarchart that features only lines, with no bars. Instead of using Lee Byron's test data generator, I am keen on generating data using JSON. However, I am faced with the challenge of convert ...

Unable to authenticate client response using passportjs jwt

Looking to set up login using passport-JWT. able to successfully sign up and log in, with a token generated upon logging in and sent back to the client application. However, after the authentication request reaches the app post-login, it seems like nothin ...