打字稿 记录项目计数



是否可以在打字稿记录中找到项目计数?

例如像

const testRecord: Record<string, string> = {
'one': 'value1',
'two': 'value2'
};
var length = testRecord.length;
// looking for length to be 2 but is undefined as there is no length property

供参考:https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

我刚刚在这里找到了这个答案,用于一个似乎工作得很好的javascript对象的长度:

JavaScript 对象的长度

我回答上面示例的实现是:

const testRecord: Record<string, string> = {
'one': 'value1',
'two': 'value2'
};
var length: Object.keys(testRecord).length;
// length equals 2

但是,请让我知道是否有更好,更具体的"记录"方法来执行此操作?

也许这不是您想要的,但是有一个具有 size 属性的 Map 类型。

你可以像这样使用它:

let m = new Map<string, any>();
m.set('a', 1)
let one = m.get('a');
console.log('a value is: ' + one + '; size of the map is: ' + m.size);

地图不像 Object 那样工作,所以先看看行为的差异: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#objects_vs._maps

最新更新