我想编写一个函数,它将接受类实例作为参数,但不允许普通的、匿名类型的对象。
例如:
class Dog {
constructor(name: string, breed: "husky" | "boxer") {
this.name = name;
this.breed = breed;
}
name: string;
breed: "husky" | "boxer";
}
class Cat {
constructor(name: string, breed: "siamese" | "persian") {
this.name = name;
this.breed = breed;
}
name: string;
breed: "siamese" | "persian";
}
function pat(pet: NoPlainObjects) {
document.write(pet.constructor.name);
}
pat(new Dog('Fido', 'boxer')); //works
pat(new Cat('Spot', 'persian')); //works
pat({name: 'snuffaluffagus'}); //compile error
最佳答案
Is it possible to have a function accept class instances, but not accept plain objects?
目前这是不可能的,因为 TypeScript 使用结构子类型。这意味着使用类构造函数创建的对象与普通的旧 JavaScript 对象文字兼容,前提是两者都具有兼容的属性。
这是文档所说的about type compatibility :
The basic rule for TypeScript’s structural type system is that x is compatible with y if y has at least the same members as x. To check whether y can be assigned to x, the compiler checks each property of x to find a corresponding compatible property in y... The same rule for assignment is used when checking function call arguments. [empahsis added]
您的问题提出了一个问题:为什么您希望函数接受类实例并拒绝普通的旧 JavaScript 对象?
关于typescript - 是否可以让函数接受类实例,但不接受普通对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56678219/