How to catch invalid serlialized data input with types

Viewed 19

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?

1 Answers

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);
Related