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

184
Visualizações
Recommended way of parsing a Form into an URLSearchParam object in Typescript

I'm learning typescript translating an old project from JS to TS. I'm having problems with this function that is called when a submit button is pressed in a login form with the default behaviour prevented. When called, the event is passed as parameter.

In the body of the function I'm trying to parse the content of the <form> into an URLSearchParam object.

function sendLogin(e: SubmitEvent) {
    let URLSP: URLSearchParams;
    if (e.target instanceof HTMLFormElement) {
        URLSP = new URLSearchParams(new FormData(e.target));
...

This approach (the one of the original JS app) is clean but doesn't work because TS complains about: URLsearchParams doesn't accept FormData datatype as argument.

function sendLogin(e: SubmitEvent) {
    let URLSP: URLSearchParams;
    if (e.target instanceof HTMLFormElement) {
        let A = new FormData(e.target);
        let B = [...A.entries()];
        let URLSP = new URLSearchParams(B);
    }
...

This second approach also doesn't work because B has [String,FormDataEntryValue][] datatype. URLSearchParams accepted datatypes are string | URLSearchParams | string[][] | Record<string, string>.

Which would be the cleanest way to parse my <form> into an URLSearchParam object in TS?

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

0

FormData is actually not full compatible with URLSearchParams contructor, sadly. See Typescript #30584 for more info.

That issue thread has a few workarounds, such as:

const convertedFormEntries = Array.from(
  formData,
  ([key, value]) => (
    [key, typeof value === 'string' ? value : value.name]
  ),
);

Which seems to work, as far as I can tell.

Playground

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