从对象的嵌套属性创建TypeScript类型

2ekbmq32  于 2023-05-19  发布在  TypeScript
关注(0)|答案(1)|浏览(154)

这就是那个物体

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,
  },
};

目标是得到以下类型

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

任何帮助都很感激

flseospp

flseospp1#

一种方法是将其转换为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'

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

相关问题