Home > Software engineering >  How to add type to make below code not prompt type errors in typescript
How to add type to make below code not prompt type errors in typescript

Time:05-18

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,
    },
  ],
});
// How to add type to make below code not prompt type errors in typescript. In typescript, this code below will prompt type errors.
console.log(obj["Scope1"].functionName(["firstParam"]));

How to add type to make that code not prompt type errors in typescript. obj extend methods, all the methods were putted in one property.

CodePudding user response:

You have a very generic Requirement regarding how the extend() work.

To avoid the type errors and make it generic we can define an ObjectTemplate to satisfy the Typescript compiler so that we can assign a value to the object on the fly.

type Args = {
    property: string;
    methods: { name: string; call: string; params: 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.call   "____"   params.length;
    });
  }
};

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

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

enter image description here

  • Related