When you write:
let obj1: MyClass = { action: "act1" };
You are using the class MyClass as a type, in the sense that you're telling the compiler that the variable obj1 complies with the MyClass type. It has to have all the mandatory fields of the class and cannot have any not known properties.
This is nice because if the type would have 200 properties, the intellisense could hint you about missing properties, for instance.
Now, MyClass is actually a class, so it does not only work as a type/interface. It also has some functionality, i.e. you can invoke the constructor and you can use extends when declaring the class.
Now, default properties of a class aren't default properties for the type. If you try to add a initializer in a typescript interface or type, you will see an error; instead, when you add a default property to a class, it means that an instance will have that property initialized to the default value only when called from the constructor.
So, there are some things you can do to fix the issue:
- You may continue using
MyClass as a type in that scenario, but then you need to still declare the name prop in the object literal:
let obj1: MyClass = {action: "act1", name: "first"};
If you do so, you still will face a:
Object literal may only specify known properties
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");
While you can in some scenarios have a valid reason to use classes as types/interfaces, you should probably call the class constructor when possible -like in this example-, or, as a comment suggest, use an interface for this.
In this case, I think you should prefer to call the constructor.
- If you only need the type to get compiler checks/intellisense on the variable type, you can use an interface:
interface MyCustomType {
name: string;
action?: string;
}
So you get a warning if you try to type a variable as MyCustomType without the name:
let obj: MyCustomType = {
action: 'act1',
} // error, you need to set 'name' since it is a mandatory field
You can set an object with or without action, since it is optional (due to the '?' in the declaration).
You cannot add unknown fields:
let obj: MyCustomType = {
name: 'name',
value: 1, // error, unknown field
}
nameparameter to be optional :name?:string = "myname".