打字稿记录项目计数

Ste*_*ans 5 typescript-generics typescript2.0

是否可以在 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
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*ans 11

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

JavaScript 对象的长度

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

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

var length: Object.keys(testRecord).length;
// length equals 2
Run Code Online (Sandbox Code Playgroud)

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