Извлечение типов из значений объекта - TypeScript, Babel - PullRequest
0 голосов
/ 09 апреля 2020

Как извлечь или получить типы из значений объекта.

Например,

const Animals = {
  C: 'cat',
  D: 'dog'
};

// to a type like this
type TAnimal = 'cat' | 'dog';

С обычным TS C Я могу это сделать,

const Animals = {
  C: 'cat',
  D: 'dog'
} as const;

type TAnimal = typeof Animals[keyof typeof Animals];

Но Бабель не позволяет as const. Я пытался использовать @babel/plugin-transform-typescript, но безрезультатно.

Предложить мне решение, которое будет работать с Babel.


Сведения о проекте

Boiler Plate: create-react-app с customize-cra

@babel/plugin-transform-typescript: 7,9,4

@babel/preset-typescript: 7,9,0

Я знаю, cra поставляется с обоими предустановленными для машинописи. Но это все равно не работает ни в одном случае.

.babelrc.js

const presets = ['@babel/preset-typescript'];

const plugins = [
  ['@babel/plugin-proposal-pipeline-operator', { proposal: 'minimal' }],
  ['@babel/plugin-proposal-optional-chaining', { loose: false }],
  ['@babel/plugin-transform-typescript'],
  '@babel/plugin-proposal-do-expressions',
  '@babel/plugin-proposal-nullish-coalescing-operator',
  // ? Tree Shaking of modules, add lodash too, if we install it
  [
    'babel-plugin-transform-imports',
    {
      '@material-ui/core': {
        transform: '@material-ui/core/esm/${member}',
        preventFullImport: true,
      },
      '@material-ui/icons': {
        transform: '@material-ui/icons/esm/${member}',
        preventFullImport: true,
      },
    },
  ],
];

module.exports = { presets, plugins };

Мои попытки

Попытка 1

Попытка " Массив TypeScript для строкового литерала типа"

const AnimalValues = [...Object.values(Animals)] as const;
type AnimalTypes = typeof AnimalValues[number];

// type AnimalTypes = string

Попытка 2

type AnimalKeys = keyof typeof Animals;
type AnimalTypes = typeof Animals[AnimalKeys];

// type AnimalTypes = string

Попытка 3

const tuple = <T extends string[]>(...args: T) => args;
const AnimalsTuple = tuple(...Object.values(Animals))
type AnimalTypes = typeof AnimalsTuple[number]

// type AnimalTypes = string
...