I have an indexable type in TypeScript with keys that can either be strings or numbers, like so:
export type MyRecords = { [name: string]: string | number };
const myRecords: MyRecords = {
foo: 'a',
bar: 1,
};
I want to create a string literal type that includes only the string keys of this type, so that I can use it to ensure type safety in my code. For example:
type KeysOfMyRecords = /* ??? */;
const key: KeysOfMyRecords = 'foo'; // should be OK
const invalidKey: KeysOfMyRecords = 'invalid'; // should cause a error
I have tried the following without success:
type KeysOfMyRecords = keyof typeof myRecords;
Would this be possible?