My TypeScript
code is compiling correctly with a focus on strict typing.
When defining the user1
instance, I am successfully forced to include all members for IUser
. If any properties are missing, such as the id
property, the TypeScript
linter throws an error:
TSError: ⨯ Unable to compile TypeScript:
error TS2322: Type '{ username: string; password: string; email: string; age: number; }' is not assignable to type 'IUser'.
Property 'id' is missing in type '{ username: string; password: string; email: string; age: number; }'.
However, for the user associated with "Steve Jobs," I didn't use the property id
, yet no error was thrown by the linter.
I'm seeking a way to define a user dynamically like the second user (without declaring another variable) while maintaining strict typing. I have attempted using angle brackets without success.
interface IUser {
id: number;
username: string;
password: string;
email: string;
age: number;
}
let user1: IUser = {
id: 1,
username: 'Bill Gates',
password: 'windows',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a5aeababa0a6b3a2b487aaaea4b5a8b4a8a1b3e9a4a8aa">[email protected]</a>',
age: 61
};
var outputObject = function(obj: any) {
console.log(JSON.stringify(obj));
}
outputObject(user1);
outputObject(<IUser> {
username: 'Steve Jobs',
password: 'mac',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="324146574457585d5041725342425e571c515d5f">[email protected]</a>',
age: 62
});
Any suggestions on how to achieve this?
Thank you!