Is it possible to use `keyof` operator on literals instead of interfaces?

keyof operates on types, but foo is a value. But the typeof operator takes a value and produces its type, so you can use keyof typeof foo to do this.

Note that this only works if you haven't associated an interface with the object literal (thanks radicand).


a bit off, while i'm finding indexer key to literals, but put it here for future reference.

const foo = {
  "hello": "hola"
};

let data: { [key in keyof typeof foo]:number} & { name: string, index: number }[] = [] as any;

data.foo = 1;
data[0] = {name:'foo', 1};

Tags:

Typescript