“任何"与“对象" [英] 'any' vs 'Object'

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

问题描述

我正在查看 TypeScript 代码并注意到它们使用:

I am looking at TypeScript code and noticed that they use:

interface Blablabla {

   field: Object;

}

使用 Objectany 的好处是什么,例如:

What is the benefit of using Object vs any, as in:

interface Blablabla {

  field: any;

}

推荐答案

Objectany 限制更多.例如:

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

Object 类没有 nomethod() 函数,因此转译器会产生一个错误来告诉你.如果您使用 any 代替,您基本上是在告诉转译器一切正常,您没有提供有关 a 中存储的内容的信息 - 它可以是任何东西!因此,转译器将允许您使用定义为 any 的内容做任何您想做的事情.

The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

简而言之

  • any 可以是任何东西(您可以在其上调用任何方法等而不会出现编译错误)
  • Object 公开在 Object 类中定义的函数和属性.
  • any can be anything (you can call any method etc on it without compilation errors)
  • Object exposes the functions and properties defined in the Object class.

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

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