从索引对象值获取联合类型

WHI*_*LOR 5 typescript

假设我有一个索引类型:

type X = {
 a: 'A',
 b: 'B'
}
Run Code Online (Sandbox Code Playgroud)

是否可以从中得到(派生):

type V = 'A' | 'B'
Run Code Online (Sandbox Code Playgroud)

不使用显式方法,如:

type V = X['a'] | X['b']
Run Code Online (Sandbox Code Playgroud)

我想要的是keyof(用于获取键联合类型),但对于值.

lfe*_*445 44

我意识到这个问题已经得到了回答,但是如果您正在寻找一种方法将联合范围缩小到实际值而不是基元,并且您正在使用不可变状态,您可以这样做:

const X = {
  a: 'A', 
  b: 'B'
  // mark properties as readonly, otherwise string type inferred 
} as const

type XValues = typeof X[keyof typeof X]

// "A" | "B
Run Code Online (Sandbox Code Playgroud)

或者,如果您同时使用可变副本和不可变副本,创建单独的只读类型可能会很有用:

const X = {
  a: 'A',
  b: 'B'
} 

type X = Readonly<typeof X>

type XValues = keyof X  

// "A" | "B
Run Code Online (Sandbox Code Playgroud)


Tit*_*mir 13

您可以使用类型查询,结果为keyof:

type V = X[keyof X]
Run Code Online (Sandbox Code Playgroud)

通常,类型查询将返回所有可能字段类型的并集,因此X['a'] | X['b']X['a' | 'b'].这就是为什么X[keyof X]工作,因为keyof将返回表示对象中所有键的字符串文字类型的并集.