nagylzs
nagylzs

Reputation: 4180

TypeScript - howto express array of member names (keys) for a type

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?

Upvotes: 0

Views: 46

Answers (1)

Lu&#239;s
Lu&#239;s

Reputation: 2843

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:

Upvotes: 1

Related Questions