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

>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

Leave a Reply