Imagine this interface:
interface IUser {
id: string;
name: string;
age: number;
}
We can have this function:
const fetchUser1 = (userId: string): IUser => {
return {
id: userId,
name: 'John',
age: 32,
};
}
This function cannot return properties that are not in the IUser interface.
So if we try to return for instance a new property the city:
const fetchUser2 = (userId: string): IUser => {
return {
id: userId,
name: 'John',
age: 32,
city: 'Hollabrunn', // TS Error
};
}
We get the TS error: Object literal may only specify known properties, and 'city' does not exist in type 'IUser' where is absolutely what we want.
Now let's try to make a Type for this function.
type TFetchUser = (userId: string) => IUser;
And implement a function of this Type, also returning by mistake the city property.
const fetchUser3: TFetchUser = (userId) => {
return {
id: userId,
name: 'John',
age: 32,
city: 'Hollabrunn',
};
};
Now here is the problem, we don't have any TS Error. The city property is allowed!
Although if we mistyped the name property to fullName we get the TS Error Property 'name' is missing in type....
Googling, I found some references about this strange behavior of the interfaces, but not a clear resolution.
Could you help?