首页 > 解决方案 > 如何使用来自普通对象的值创建类型?

问题描述

我有一个这样的对象:

const myObject = {
  0: 'FIRST',
  10: 'SECOND',
  20: 'THIRD',
}

我想用这个对象值创建一个类型,如下所示:

type AwesomeType = 'FIRST' | 'SECOND' | 'THIRD';

如何做到这一点?

标签: typescript

解决方案


要获取变量(对象)类型,您可以使用typeofoperator。为了防止文字类型扩大,您可以使用as const断言

const myObject = {
  0: 'FIRST',
  10: 'SECOND',
  20: 'THIRD',
} as const;

type Values<T> = T[keyof T];

type AwesomeType = Values<typeof myObject>; // "FIRST" | "SECOND" | "THIRD"

操场


推荐阅读