Typescript 从对象推断值

Typescript 从对象推断值,typescript,Typescript,如何从这样的对象推断所有值 const fruits = { a: 'apple', b: 'banana' }; …这样我就能得到这个 type fruitValues = 'apple' | 'banana'; (我相信我正在寻找流中的等价物$Values)您可以从对象推断类型,但该对象已被推断为仅包含字符串属性。也就是说,如中所述,“apple”和“banana”类型已扩展为字符串,因为它们是非只读属性 const fruits = { a: 'apple', b: '

如何从这样的对象推断所有值

const fruits = {
  a: 'apple',
  b: 'banana'
};
…这样我就能得到这个

type fruitValues = 'apple' | 'banana';

(我相信我正在寻找流中的等价物
$Values

您可以从对象推断类型,但该对象已被推断为仅包含
字符串
属性。也就是说,如中所述,
“apple”
“banana”
类型已扩展为
字符串,因为它们是非
只读属性

const fruits = {
  a: 'apple',
  b: 'banana'
};

type FruitValues = (typeof fruits)[keyof typeof fruits]; // string
因此,上面的
不是您想要的。如果你想靠得更近,你需要防止这种扩大。一种方法是使用冗余但独立的:

另一种方法是生成一个辅助函数,用于推断更窄的类型:

// put in a library somewhere
type Narrowable = string | number | boolean | undefined | null | void | {};
const narrowObj = <V extends Narrowable, T extends { [k: string]: V }>(t: T) => t;

const fruits = narrowObj({
  a: 'apple',
  b: 'banana'
})

type FruitValues = (typeof fruits)[keyof typeof fruits]; // "apple" | "banana"

好的,希望能有帮助。祝你好运

太棒了!我已经试着找这个很久了!
// put in a library somewhere
type Narrowable = string | number | boolean | undefined | null | void | {};
const narrowObj = <V extends Narrowable, T extends { [k: string]: V }>(t: T) => t;

const fruits = narrowObj({
  a: 'apple',
  b: 'banana'
})

type FruitValues = (typeof fruits)[keyof typeof fruits]; // "apple" | "banana"
const fruits = {
  a: 'apple',
  b: 'banana'
} as const; // requires TS3.4+

type FruitValues = (typeof fruits)[keyof typeof fruits]; // "apple" | "banana"