When working with TypeScript, it is important to note that an object literal can be assigned to a class typed variable as long as the object provides all properties and methods required by the class.
class MyClass {
a: number;
b: string;
}
// The compiler will not raise an error
const instance: MyClass = { a: 1, b: '' };
// Even if the object has additional properties, the compiler will not complain
const literal = { a: 1, b: '', c: false };
const instance2: MyClass = literal;
However, there may be instances where you want to prevent such assignments for two main reasons:
- The expression
instance instanceof MyClass
should evaluate to true; - Avoiding the assignment of objects with extra properties (as seen above).
To enforce stricter type checking similar to how interfaces work in TypeScript, one might wonder if there is a way to restrict this behavior. Is there a solution to achieve this?