How do I get the key of a value in a Typescript Record

Object.keys returns string[] not Array<keyof T> (where T is the type of the value passed in). The reasons for this are outlined here.

Since your object is probably not going to have unknown keys, you can use a type assertion:

export type Period = 'dy' | 'wk' | 'mn' | 'qt' | 'yr';

const periods: Record<Period, string> = {
  dy: 'Day',
  wk: 'Week',
  mn: 'Month',
  qt: 'Quarter',
  yr: 'Year'
};

const key = (Object.keys(periods) as Array<Period>).find(key => periods[key] === 'Day');

Playground Link

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)