将对象转换为联合类型

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

我有打字稿的问题。我想从对象值创建像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
}

就像是:

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

但对于对象。任何提示都是受欢迎的。

typescript typescript-typings
2个回答
1
投票

要获得变量类型中的值的并集,可以使用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
}

从评论中你想要的文字类型(1 | 2 | "a string")不是基本类型。为此,您需要更改类型pf x以包含文字类型。最简单的方法是在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
}

1
投票

我想这就是你需要的:

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

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

type XValues = ValueOf<typeof xx>; 
© www.soinside.com 2019 - 2024. All rights reserved.