将对象转换为联合类型

Geo*_*mov 0 typescript typescript-typings

我有一个关于打字稿的问题。我想从对象值创建类似 union 的东西。我怎么能做到这一点?例如:

const x = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
}

const y = (y: the value which exist of x ): boolean => {
  return true
}
Run Code Online (Sandbox Code Playgroud)

就像是:

type ValueOf<T> = T[keyof T]; 
Run Code Online (Sandbox Code Playgroud)

但对于对象。欢迎任何提示。

Tit*_*mir 9

要获得变量类型中值的联合,您可以使用ValueOf<typeof x>. 对于您的示例,该类型将是string | number | HTMLDivElement

const x = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
}
type ValueOf<T> = T[keyof T]; 
const y = (P: ValueOf<typeof x>): boolean => { // p:  string | number | HTMLDivElement
   return true
}
Run Code Online (Sandbox Code Playgroud)

从注释中您需要文字类型 ( 1 | 2 | "a string") 而不是基本类型。为此,您需要更改类型 pfx以包含文字类型。最简单的方法是在 3.4 中添加一个const断言:

const x = {
    x: 1,
    y: 2,
    z: 'a string',
    k: document.createElement('div')
} as const
type ValueOf<T> = T[keyof T];
const y = (p: ValueOf<typeof x>): boolean => { // p:  1 | 2 | "a string" | HTMLDivElement
    return true
}
Run Code Online (Sandbox Code Playgroud)