I am fairly new to typescript and have scoured the web trying to find an explanation for this.
Recently I have been working on a project and have wanting to use sequelize with it. When reading through the typescript section of the documents, I came across this example below:
// These are all the attributes in the User model
interface UserAttributes {
id: number;
name: string;
preferredName: string | null;
}
// Some attributes are optional in `User.build` and `User.create` calls
interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}
class User extends Model<UserAttributes, UserCreationAttributes>
implements UserAttributes {
public id!: number; // Note that the `null assertion` `!` is required in strict mode.
public name!: string;
public preferredName!: string | null; // for nullable fields
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
//other code
}
Inside the class, the preferredName
also has the non-null assertion operator but then proceeds to include null in its type.
Does that override the static type checking because it could possibly be null at runtime (i.e. the user doesn't have a preferred name)?
Or is there a better explanation about why they would include the non-null operator on that property? Such as to exclude undefined but include null.
preferredName
is not null – Caseate