Is it possible to infer the keys of a Record in TypeScript?

You can use a helper function when defining the object. The function will have a type parameters that mandates all properties must be of type CSSProperties using an index signature. Since the function is generic the result will be typed correctly (it will not actually have an index signature but rather just the defined properties)

function createStyleMap<T extends { [name: string]: CSSProperties }>(cfg: T)  {
  return cfg;
}
const style = createStyleMap({
  root: {
  background: 'red'
  },
  title: {
    fontWeight: 'bold'
  }
});

style.root //ok
style['hu'] // error

You can also type it to return Record but I don’t think this would add any value

function createStyleMap<T extends { [name: string]: CSSProperties }>(cfg: T) : Record<keyof T, CSSProperties> {
  return cfg;
}

Leave a Comment

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