Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create TypeScript type from object's nested properties

This is the object


export const fieldMapping = {
  'IP': { name: 'ipAddress', type: AirtableFieldType.STRING },
  'IP Country': { name: 'country', type: AirtableFieldType.STRING },
  'IP City': { name: 'city', type: AirtableFieldType.STRING },
  'IP Continent': { name: 'continent', type: AirtableFieldType.STRING },
  'Payment Processor': {
    name: 'paymentProcessor',
    type: AirtableFieldType.STRING,
  },
};

the goal is to get the following type

type fieldNames = | 'ipAddress' | 'country' | 'city' | 'continent' | 'paymentProcessor';

any help is appreciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way would be casting it as const.

const AirtableFieldType = {
    STRING: 'sample'
}

export const fieldMapping = {
  'IP': { name: 'ipAddress', type: AirtableFieldType.STRING },
  'IP Country': { name: 'country', type: AirtableFieldType.STRING },
  'IP City': { name: 'city', type: AirtableFieldType.STRING },
  'IP Continent': { name: 'continent', type: AirtableFieldType.STRING },
  'Payment Processor': {
    name: 'paymentProcessor',
    type: AirtableFieldType.STRING,
  },
} as const;


type FieldKeys = keyof typeof fieldMapping // get all the keys of fieldMapping
type FieldMapping = (typeof fieldMapping)[FieldKeys]['name'] // 'ipAddress' | 'country' | 'city' | 'continent' | 'paymentProcessor'

Demo TypeScript:

https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBAQQJYCcYEMBGAbApgMSV2wBMAVATwAdc4BeOAb2DlbgGUyAlASQDkA4gC44AcijoAtlTyjgAX2DBcADypg0ccNHgAzIqQCy6KlSQQA5vSYsxPAAqiRjOBCm4RopFQQkSKXCgoUQAaOBhqD0RUDBwCA3JIgDpOXkE4eRDbUQc4AGEwAFcIGBQKJyZXd09wYtLysIiaEWQ0LDxCYkSaFO5+AQys1hz7fKQIipc3SSjREHGG8MiWmPb4rsoe1P7B7NyCkvNcEsmqmZrIGCOTxuXotrjO0k3cXrSBzOz7dAoZkrh7CgwCBAlANJNbKxprMqD8-jBAcDQeChmwmlFWrEOgkXm9+qjPvI4OgoFpILAANxKYDouBPEgAaVwFFJDAA1sywLoljQuXB9F1jKZzBYaZE6QkhSLrAAKdF8gVGExmSwASgA2vSmSyALrq0TQ0Q64BAA

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading