【发布时间】:2022-01-13 13:56:43
【问题描述】:
所以来自:
export interface Category{
val: string;
icon: string
}
const categoryArray: Category[] = [
{
val: 'business',
icon: 'store'
},
{
val: 'media',
icon: 'video'
},
{
val: 'people',
icon: 'account'
},
...
我想像这样返回一个 Union 类型:
'business' | 'media' | 'people' ...
我不知道有什么样的语法或帮助器,也许根本没有。我意识到这种方式可能是倒退的,也许应该使用枚举,但在此之前,我想知道它是可能的。
我想做的一些虚构示例,但我希望解决方案更复杂
type Cats = keysof[] categoryArray 'val'
type Cats = valuesof categoryArray 'val'
以下是关闭的,但返回string:
export type CatsValType = typeof categories[number]['val']
或以下;而不是我需要字符串文字的类型
type ValueOf<T> = T[keyof T];
type KeyTypes = ValueOf<typeof categories[number]> // Returns: `string`
有类似的问题,例如:Is there a `valueof` similar to `keyof` in TypeScript?,但它们不假设对象数组。
和这里的例子:https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html 类似,但我不想返回类型,而是字段的值,所以我得到一个 Union 类型返回。
【问题讨论】:
标签: typescript typeof union-types keyof