Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
How to add type to make below code not prompt type errors in typescript
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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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"]));

Code Playground

about 4 years ago · Juan Pablo Isaza Relatório

0

According to typescript-interface-problem I find one answer.


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

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

    return newObject;
  },
};

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

After that, we can get this.

enter image description here

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda