空接口允许任何对象? [英] Empty interface allow any object?

查看:31
本文介绍了空接口允许任何对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么空接口不需要对象为空?

Why empty interface doesn't require object to be empty?

interface A {};
const a: A = {a: 1};
console.log(a);

是有效的代码,将输出{ a: 1 }.

is valid code and will output { a: 1 }.

我认为添加可选属性应该可以正常工作,但是

I would assume that adding optional property should work fine, but

interface A {};
interface B extends A {
    b?: any;
}
const a: B = {a: 1};
console.log(a);

以错误结束 Type '{ a: number;}' 不能分配给类型 'B'.

  • 如果接口定义了对象必须具有的属性,B 情况应该可以正常工作,所有必需的属性都存在.
  • 如果接口定义了对象可以拥有的属性,A case 应该会导致错误,a 没有在接口中定义.
  • If interface define what properties object must have, B case should work fine, all required properties are present.
  • If interface define what properties object can have, A case should result in error, a is not defined in interface.

非空接口定义了对象可以和必须具有什么.空接口的行为类似于 any.

Non empty interface defines both what object can and must have. Empty interface behaves like any.

有没有解释为什么空界面会这样?这是故意的还是只是一个错误?

Is there explanation why empty interface behaves like this? Is this intentional or just a bug?

推荐答案

这种行为是故意的.

当目标是空对象类型时,不会执行多余的属性检查,因为很少有意图只允许空对象.

The excess property check is not performed when the target is an empty object type since it is rarely the intent to only allow empty objects.

实际上,你可以{a: 1}赋值给B,这里的其他答案大多是错误的.

Actually, you can assign {a: 1} to B, the other answers here are mostly wrong.

您在 TypeScript 中偶然发现了另一个稍微令人困惑的怪癖,即您不能直接分配对象字面量给类型,其中对象字面量包含除类型中指定的属性之外的其他属性.

You have stumbled upon another slightly confusing quirk in TypeScript, namely that you can not directly assign an object literal to a type where the object literal contains other properties than the one specified in the type.

但是,您可以将对象的任何现有实例分配给类型,只要它满足该类型即可.

However, you can assign any existing instance of an object to a type, as long as it fulfill the type.

例如:

interface Animal {
    LegCount: number;
}

let dog: Animal = { LegCount: 4, Fur: "Brown" }; // Nope

var myCat = { LegCount: 4, Fur: "Black" };
let theCat: Animal = myCat; // OK

当您的类型为空时,此约束将被简单地忽略.

This constraint is simply ignored whey you have a type that is empty.

阅读更多此处这里.

Typescript 团队的后续回答可在 GitHub 上获得.

A later answer from the Typescript team is available on GitHub.

这篇关于空接口允许任何对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆