从对象数组中获取字符串文字类型

Try*_*ace 8 typeof typescript union-types keyof

所以来自:

export interface Category{
  val: string;
  icon: string
}
const categoryArray: Category[] = [
  {
    val: 'business',
    icon: 'store'
  },
  {
    val: 'media',
    icon: 'video'
  },
  {
    val: 'people',
    icon: 'account'
  },

  ... 
Run Code Online (Sandbox Code Playgroud)

我想像这样找回 Union 类型:

'business' | 'media' | 'people' ... 
Run Code Online (Sandbox Code Playgroud)

我不知道有什么样的语法或帮助程序,也许根本没有。我意识到这种方式可能是倒退的,也许应该使用枚举,但在此之前,我想知道这是可能的。

我想做的一些虚构的例子,但我希望解决方案更加复杂

type Cats = keysof[] categoryArray 'val'  
type Cats = valuesof categoryArray 'val'
Run Code Online (Sandbox Code Playgroud)

以下内容很接近,但返回string

export type CatsValType = typeof categories[number]['val']
Run Code Online (Sandbox Code Playgroud)

或以下;我需要字符串文字而不是类型

type ValueOf<T> = T[keyof T];
type KeyTypes = ValueOf<typeof categories[number]> // Returns: `string`
Run Code Online (Sandbox Code Playgroud)

还有类似的问题,例如:TypeScript 中是否有类似于“keyof”的“valueof”?但他们不假设对象数组。

这里的示例: https: //www.typescriptlang.org/docs/handbook/2/indexed-access-types.html类似,但我不想返回类型,而是返回字段的值,所以我得到了一个 Union 类型。

T.J*_*der 7

你可以这样做,如果

\n
    \n
  • 数组中的值在运行时不会改变(因为类型信息对于 TypeScript 来说只是编译时的事情);和

    \n
  • \n
  • 你告诉 TypeScript 它们的值不会通过使用而改变as const;改变。和

    \n
  • \n
\n
    \n
  1. categoryArray常量 type Category[],因为如果你这样做,结果只会是string(因为Category["val"]\ 的类型是string)而不是您想要的字符串文字联合类型。
  2. \n
\n

这是一个示例(游乐场链接):

\n
export interface Category{\n  val: string;\n  icon: string\n}\nconst categoryArray = [\n  {\n    val: \'business\',\n    icon: \'store\'\n  },\n  {\n    val: \'media\',\n    icon: \'video\'\n  },\n  {\n    val: \'people\',\n    icon: \'account\'\n  },\n] as const;\n\ntype TheValueUnion = (typeof categoryArray)[number]["val"];\n//   ^? \xe2\x88\x92\xe2\x88\x92 "business" | "media" | "people"\n
Run Code Online (Sandbox Code Playgroud)\n

关键位是as consttype TheValueUnion = (typeof categoryArray)[number]["val"];,其分解如下:

\n
    \n
  1. typeof categoryArray得到类型categoryArray(推断类型,因为我们没有分配特定类型)。
  2. \n
  3. [number]访问按类型上的数字索引的类型的并集categoryArray
  4. \n
  5. ["val"]从 #2访问val联合属性的类型联合,这是您想要的字符串文字类型:"business" | "media" | "people"
  6. \n
\n