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

247
Visualizações
How to catch invalid serlialized data input with types

Even while type MyRequest requires the ID attribute the function process is able to declare the variable of type MyRequest even while the ID attribute is missing:

export type MyRequest = 
  {
    ID: string, 
    Name?: string
  };

function process(jsonData:string) {
  try {
    let data: MyRequest = JSON.parse(jsonData);
    return data
  } catch (err) {
    console.log("Error:", err)
  }
}

let jsonData = JSON.stringify( { foo: "bar" } );
let result = process(jsonData);
console.log(result);

How to edit the function process so it errors if the incoming string data doesn't contain the ID attribute required by the type MyRequest?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

JSON.parse is a JavaScript function, your interface is TypeScript. JavaScript has no way of interacting with the interface at run time in order to enforce that all properties on your interface exist when parsing, so it cannot produce an error in the way you have your example laid out.

In order to do this, you'd need to have JavaScript checks that validate your parsed JSON matches what is expected. Something like

export type MyRequest = 
  {
    ID: string, 
    Name?: string
  };

function isMyRequest(json: any): json is MyRequest {
    return json && Object.prototype.hasOwnProperty.call(json, 'ID');
}

function process(jsonData:string) {
  try {
    let data: MyRequest = JSON.parse(jsonData);
    if (!isMyRequest(data)) {
        throw new Error('invalid jsonData');
    }
    return data;
  } catch (err) {
    console.log("Error:", err)
  }
}

let jsonData = JSON.stringify( { foo: "bar" } );
let result = process(jsonData);
console.log(result);
over 4 years ago · Santiago Trujillo 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