在TypeScript中,如果对象文字提供了类所需的所有属性和方法,则可以将其分配给类类型的变量。
class MyClass {
a: number;
b: string;
}
// Compiler won't complain
const instance: MyClass = { a: 1, b: '' };
// Compiler won't complain if I assign an object with more properties
const literal = { a: 1, b: '', c: false };
const instance2: MyClass = literal;
我在这里要做的是基于两个原因来防止这种分配:
instance instanceof MyClass
应该为真; 通过这种方式,TypeScript类的工作方式更像一个接口。有什么办法可以防止这种情况?
答案 0 :(得分:0)
我不知道我是否正确理解了您的问题,但是我从您的代码中得出的结论是
在第二次分配中,变量literal
未定义为类型MyClass
const literal = { a: 1, b: '', c: false };
因此,您只是尝试创建具有某些值的const变量。
答案 1 :(得分:0)
在the TypeScript docs中,您观察到的似乎是预期的行为:
TypeScript中的类型兼容性基于结构子类型。结构化类型是仅根据其成员关联类型的一种方式。
因此,如果两种类型具有相同的结构,则意味着可以将这些类型的对象彼此分配。
一旦开始将私有成员添加到类中(您几乎总是在实践中这样做),类型检查将更接近您想要的方式。
class MyClass {
a: number;
b: string;
private c: number;
}
// "Property 'c' is missing in type '{ a: number; b: string; }' but required in type 'MyClass'."
const instance: MyClass = { a: 1, b: '' };
// "Property 'c' is private in type 'MyClass' but not in type '{ a: number; b: string; c: number; }'"
const literal: MyClass = { a: 1, b: '', c: 3 };
class OtherClass {
a: number;
b: string;
private c: number;
}
// "Types have separate declarations of a private property 'c'"
const otherClass: MyClass = new OtherClass();