validate an unknown json object against a typescript interface in typescript in typescript

To validate an unknown JSON object against a TypeScript interface, we should first define the interface that the JSON object should conform to. We can use the interface keyword to define the structure and data types of the expected JSON object.

index.ts
interface MyData {
  name: string;
  age: number;
  hasPets: boolean;
}
72 chars
6 lines

Next, we need to define a function that will perform the validation. We can use the JSON.parse() method to convert the incoming JSON string into an object, and then use the Object.assign() method to assign the JSON object to a new object that conforms to our TypeScript interface. If any fields are missing or have incorrect data types, TypeScript will throw an error.

index.ts
function validateData(jsonString: string): MyData {
  const jsonData = JSON.parse(jsonString);
  const data: MyData = Object.assign({}, jsonData);
  return data;
}
164 chars
6 lines

Finally, we can call the validateData() function with the incoming JSON string, and it will return a new object that conforms to our TypeScript interface, or it will throw an error if the validation fails.

index.ts
const jsonString = '{"name": "Alice", "age": 30, "hasPets": true}';
const data = validateData(jsonString);
console.log(data); // { name: "Alice", age: 30, hasPets: true }
171 chars
4 lines

gistlibby LogSnag