typescript - 是否可以让函数接受类实例,但不接受普通对象?

标签 typescript

我想编写一个函数,它将接受类实例作为参数,但不允许普通的、匿名类型的对象。

例如:

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/

相关文章:

typescript - 'object' 、{} 和 TypeScript 中的对象之间的区别

javascript - 为什么 NodeListOf 上不存在 forEach

typescript - Angular2 QuickStart 拒绝为发布候选构建

typescript - 在 Typescript 中,为什么我需要设置一个定义为只读的类的属性?

angular - typescript 包可见性(创建库)

javascript - 如何在 TypeScript 中为日期添加一天

javascript - 如何处理 ngFor 中输入类型的动态正则表达式值?

javascript - 在nodejs中等待循环内的 promise

javascript - 使用 Vue、Typescript 和 Karma 进行单元测试

javascript - 如何从源代码(而不是 bundle )运行 Electron 应用程序