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?

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

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.
I understand that the keyof in the declaration prevents from mistyping. But it does not prevent me from forgetting to add a key...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.