Middle
Tell me about TypeScript: if you declare an object User with a field id: number, and the server sends id: string — how can you find out about this in advance?
sobes.tech AI
Answer from AI
TypeScript is a statically typed language, but when working with data from a server, types are not guaranteed because data arrives in JSON format and may not match the expected types.
If we have an interface:
interface User {
id: number;
name: string;
}
and an object with id coming from the server as a string, TypeScript cannot verify this at compile time because types are checked only during development, and data arrives dynamically.
To proactively detect mismatches, data validation needs to be implemented, for example, using libraries like io-ts, zod, or manually checking types after receiving data:
function isUser(obj: any): obj is User {
return typeof obj.id === 'number' && typeof obj.name === 'string';
}
const data = JSON.parse(response);
if (!isUser(data)) {
throw new Error('Invalid user data');
}
Thus, TypeScript helps with types during development, but additional validation is necessary for server data.