简体   繁体   English

如何根据对象值创建窄类型

[英]how do I create a narrow type based on an objects values

I'm in the process of moving from flow to typescript and I've run into something I can't figure out how to do.我正在从流程转向打字稿,我遇到了一些我无法弄清楚该怎么做的事情。 In flow I had the following:在流程中,我有以下几点:

const color = Object.freeze({
  white: '#ffffff',
  black: '#000000',
})

type PossibleColorValues = $Values<typeof color>

in this case PossibleColorValues was '#ffffff' | '#000000'在这种情况下, PossibleColorValues '#ffffff' | '#000000''#ffffff' | '#000000' '#ffffff' | '#000000'

Is there an equivalent to this in typescript?打字稿中是否有与此等效的内容? I've tried the following:我尝试了以下方法:

type PossibleColorValues = typeof color[keyof typeof color]

but in this case PossibleColorValues is just string但在这种情况下, PossibleColorValues值只是string

You have the right idea about how to get a union of all possible values in an object.您对如何获得对象中所有可能值的联合有正确的想法。 typeof color[keyof typeof color] should do the trick. typeof color[keyof typeof color]应该可以解决问题。

The problem is that color does not preserve original types as it is currently defined.问题是color不保留当前定义的原始类型。 You need to convince the compiler to preserve the string literal types you originally assign in the object literal.您需要说服编译器保留您最初在对象文字中分配的字符串文字类型。

In 3.4, unreleased yet, you can use as const to let the compiler know you want literal types and a readonly object.在尚未发布的 3.4 中,您可以使用as const来让编译器知道您需要文字类型和只读对象。 So this will work as expected in 3.4 (again when 3.4 is released probably this month):因此,这将在 3.4 中按预期工作(再次可能在本月发布 3.4 时):

const color = Object.freeze({
  white: '#ffffff',
  black: '#000000',
} as const)

type PossibleColorValues = typeof color[keyof typeof color]

In the meantime you can use a function to get the compiler to infer literal types:同时,您可以使用函数让编译器推断文字类型:

declare function withLiterals<
    T extends Record<string, V>, 
    V extends string | boolean | number | symbol | null | undefined | Record<string, V>
>(input: T ): T;

const color = Object.freeze(withLiterals({
    white: '#ffffff',
    black: '#000000',
}));

type PossibleColorValues = typeof color[keyof typeof color] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM