Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Record item count

Is it possible to find the count of items in a Typescript record?

For example something like

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

For reference: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

like image 225
Stewart Evans Avatar asked Feb 03 '20 05:02

Stewart Evans


1 Answers

I've just found this answer here for the length of a javascript object which seems to work just fine:

Length of a JavaScript object

My implementation to answer the example above was:

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

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

However please let me know if there is a better, more specific "Record" way to do this?

like image 156
Stewart Evans Avatar answered Sep 24 '22 00:09

Stewart Evans