After the server responds, it will look like this:
{
code: number;
info: string;
data //appears only when code is 200
}
How can I create a type definition to specify that the data
property should only exist when code
is 200?
My current code implementation looks like this:
const res = await fetch(...)
const result:MyType = await res.json()
if (result.code != 200) {
//handle case with no data
} else {
//handle data in result.data
}
Github copilot suggests the following solution, which seems to be functional. However, I'm curious if there are alternative approaches.
type Type1 = {
code: number;
info: string;
data?: string; // Optional property
}
type Type2 = Type1 & { code: 200, data: string };
// Usage:
const obj1: Type2 = { code: 200, info: "Success" }; // Error: 'data' property is missing, but obj1 can be set as Type1
const obj2: Type1 = { code: 404, info: "Not Found" }; // Valid
const obj3: Type2 = { code: 200, info: "Success", data: "Some data" }; // Valid