I have a question regarding generic function (specifically why i'm able to modify an object from specific type)
example :
interface UserConfig {
name: string;
age: number;
}
let user: UserConfig = {
name: "Eyal",
age: 23,
};
function addTimestamp<T>(arg: T): T {
return { ...arg, timestamp: new Date().toString() };
}
console.log(user); // {name: 'Eyal',age: 23}
user = addTimestamp<UserConfig>(user);
console.log(user); // { name: 'Eyal', age: 23, timestamp: 2022-06-29T16:28:31.524Z }
Why i'm able to mutate user variable when it should have UserConfig interface properties only (name and age)
As this won't work
...
user.timestamp = "xxxx" // ERROR - Property 'timestamp' does not exist on type 'UserConfig'