← 中文资源

简体中文版本

object 类型注解排除原始值

小写 object 类型把参数限制为非原始值:字面量对象、数组、Map 都能通过,而字符串与数字会被拒之门外,大写 Object 则宽松得多。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

keys: 1
keys: 3
keys: 0
Object (capital) accepted a string: true

实现说明

全部逻辑都在函数 describe中。

使用要点

  • 演示输出是带标签的(Object (capital) accepted a string:),每个操作都会留下自己的一行标注。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 describe。

主要签名是 function describe(value: object)

核心语句

return 'keys: ' + Object.keys(value).length;

代码示例

// The lowercase object type accepts anything that is not a primitive
function describe(value: object): string {
  return 'keys: ' + Object.keys(value).length;
}

console.log(describe({ id: 7 }));
console.log(describe([1, 2, 3]));
console.log(describe(new Map([['a', 1]])));

// Primitives fail compilation against object:
// describe('text'), describe(42) and describe(null) are all rejected

// The older Object (capital) annotation is permissive and still accepts strings
const loose: Object = 'still allowed';
console.log('Object (capital) accepted a string:', typeof loose === 'string');