Consider the following scenario:
let obj1: MyClass = { action: "act1" };
In this case, you are utilizing the class MyClass
as a type. This means that you are informing the compiler that the variable obj1
adheres to the MyClass
type. It must have all the required fields of the class and cannot include any unknown properties.
This approach is beneficial because if the type consists of numerous properties, the intellisense can warn you about any missing properties.
However, it's important to note that MyClass
is not just a type or interface; it also serves as a class
. Therefore, it offers functionality such as constructor invocation and the ability to utilize extends
when defining the class.
Default properties in a class do not automatically become default properties for the type. While attempting to add an initializer in a TypeScript interface
or type
will generate an error, assigning a default property in a class ensures that an instance will have that property initialized with the default value only during construction.
There are several ways to address this issue:
- You can continue using
MyClass
as a type in this situation, but make sure to declare the name
property in the object literal as well:
let obj1: MyClass = {action: "act1", name: "first"};
Even after doing this, you may encounter:
Object literal may only specify known properties
This occurs because the action
property does not exist in MyClass
. You would need to add an action
property to MyClass
.
- Use a constructor
let obj1 = new MyClass("act1");
If possible, it is recommended to call the class constructor instead of solely using classes as types/interfaces, as shown in this example. Alternatively, consider utilizing an interface, as suggested in a comment.
In this particular scenario, invoking the constructor seems like the preferable choice.
- If your main objective is to leverage compiler checks/intellisense on the variable type, consider using an interface:
interface MyCustomType {
name: string;
action?: string;
}
This way, you will receive a warning if you attempt to assign a variable as MyCustomType
without specifying the name:
let obj: MyCustomType = {
action: 'act1',
} // error, 'name' needs to be set as it is a required field
You can choose to include or exclude the action property since it is optional (denoted by '?').
However, adding unknown fields will result in an error:
let obj: MyCustomType = {
name: 'name',
value: 1, // error, unknown field
}