0

How can I create an expression that contains an array of member names of that given type?

Example:

export type FileInfo  = {
    id: number
    title ?: string
    ext?: string|null
}
const fileinfo_fields = ["id","ext","title"];

I need to pass the field names to various methods for many different types.

Example:

const info = await api.get_info<FileInfo>(1234, fileinfo_fields);

I need this because there are too many types with too many fields, and I'm affraid of making mistakes.

I understand that type information is not available at runtime, but all I need is a constant array that contains the field names.

Something like this, just I can't figure out:

const fileinfo_fields = magic_extract_expression<FileInfo>; // ????

Is it possible somehow?

nagylzs
  • 3,954
  • 6
  • 39
  • 70

1 Answers1

1

Those "field names" are called keys. Each object has a set of "key-value" pairs. You can read out the keys of a type with TypeScript using the keyof operator.

For example:

type FileInfo = {
    id: number
    title?: string
    ext?: string|null
}

let key: keyof FileInfo; // "id" | "title" | "ext";

If you want an array of keys you can do the following:

const keys: (keyof FileInfo)[] = ["id", "title", "ext"];

You can read more on the keyof operator here in the TypeScript handbook:

Luïs
  • 2,671
  • 1
  • 20
  • 33
  • 1
    The question was about finding a way to avoid typing in the keys multiple times. I know that I can re-type the names into a constant array. I'm already doing it. – nagylzs Jun 25 '21 at 08:56
  • 1
    I understand that the keyof in the declaration prevents from mistyping. But it does not prevent me from forgetting to add a key... – nagylzs Jun 25 '21 at 08:57