Imagine I have a standard 'user' object that includes the common properties like username, email, and password. Now, I want to create a separate object that is a subset of the user object but without the password property. Here's a basic example:
interface IUserSansPassword {
username: string;
email: string;
}
class UserSansPassword implements IUserSansPassword { ... }
interface IUser extends IUserSansPassword {
password: string;
}
class User implements IUser { ... }
When attempting to assign an object of type IUserSansPassword
, I would expect the following code to result in an error:
const userSansPassword: UserSansPassword = new User(); // No TS Error †††
To my surprise, TypeScript does not produce an error in this case because it allows objects with extra properties to be assigned. This behavior contrasts with defining the object directly with the extra property as shown below:
const userSansPassword: IUserSansPassword = {
username: 'jake',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="680209030d281b0609030d460b07[email protected]">',
password: '' // TS Error ***
}
In summary, my questions are:
Why does TypeScript behave this way? Is it not problematic to allow assignment to a type with excess properties (as seen in *** above)?
Is there a specific TypeScript setting or method that can be used to generate an error for cases like ††† above?