Middle
TypeScript task: Is the call to the getUsername function with an object of type IUser (a custom consumer interface) correct if the field structure matches TUser from the library? Explain the principle of structural typing.
sobes.tech AI
Answer from AI
In TypeScript, calling a function with an object of type IUser will be correct if the structure of IUser's fields matches TUser from the library, even if they are different interfaces. This is due to the principle of structural typing used in TypeScript.
Structural typing means that type compatibility is determined not by the name of the type, but by its structure — the set of properties and their types. If an object has all the necessary fields with the correct types, it is considered compatible.
Example:
interface TUser {
id: number;
name: string;
}
interface IUser {
id: number;
name: string;
}
function getUsername(user: TUser): string {
return user.name;
}
const user: IUser = { id: 1, name: 'Alice' };
// The call is correct because the structure matches
getUsername(user);
Thus, if the fields and their types match, TypeScript will allow using an IUser object where a TUser is expected.