为什么字符串的并集与数组[数字]的类型不同?

问题描述 投票:0回答:1

打字稿游乐场

我试图建立一个字符串的并集,但令人沮丧的是这两件事是不同的......

export const RETURN_BOOL = 'RETURN_BOOL'
export const RETURN_JSON = 'RETURN_JSON'
export const RETURN_LINES = 'RETURN_LINES'
export const RETURN_STDOUT = 'RETURN_STDOUT'
export const RETURN_BASH = 'RETURN_BASH'

export type OutputItems = 
  | typeof RETURN_BOOL
  | typeof RETURN_JSON
  | typeof RETURN_LINES
  | typeof RETURN_STDOUT
    typeof RETURN_BASH

export const outputItemsArray = [
  RETURN_BOOL,
  RETURN_JSON,
  RETURN_LINES,
  RETURN_STDOUT,
  RETURN_BASH
] as const

export type OutputItems2 = typeof outputItemsArray[number]

type x = OutputItems2[]
  // ^?
type y = OutputItems[]
  // ^?

typescript
1个回答
0
投票
  1. 你在
    |
    之前忘记了
    RETURN_BASH
  2. 您可以使用映射类型来“扩展”联合:

游乐场

export const RETURN_BOOL = 'RETURN_BOOL'
export const RETURN_JSON = 'RETURN_JSON'
export const RETURN_LINES = 'RETURN_LINES'
export const RETURN_STDOUT = 'RETURN_STDOUT'
export const RETURN_BASH = 'RETURN_BASH'

export type OutputItems = 
  | typeof RETURN_BOOL
  | typeof RETURN_JSON
  | typeof RETURN_LINES
  | typeof RETURN_STDOUT
  | typeof RETURN_BASH // you forgot | here

export const outputItemsArray = [
  RETURN_BOOL,
  RETURN_JSON,
  RETURN_LINES,
  RETURN_STDOUT,
  RETURN_BASH
] as const

export type OutputItems2 = typeof outputItemsArray[number]

type x = OutputItems2[]
  // ^?
type y = {[K in OutputItems]: K}[OutputItems][] // use a mapped type to expand the type
  // ^?
© www.soinside.com 2019 - 2024. All rights reserved.