打字稿记录项目数

时间:2020-02-03 05:27:35

标签: typescript2.0 typescript-generics

是否可以找到Typescript记录中的项目数?

例如类似

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

1 个答案:

答案 0 :(得分:5)

我刚刚在这里找到了一个javascript对象的长度的答案,似乎很不错:

Length of a JavaScript object

我为回答上述示例的实现是:

const testRecord: Record<string, string> = {
    'one': 'value1',
    'two': 'value2'
  };

var length: Object.keys(testRecord).length;
// length equals 2

但是,请让我知道是否有更好的,更具体的“记录”方式来做到这一点?