【发布时间】:2022-01-21 17:09:33
【问题描述】:
我正在尝试从一个对象生成几种类型,但完全被卡住了。即使是非 TS 方式(首先生成更简单的对象/数组)并从中创建类型,似乎也不起作用。我试图避免重复存储在对象中的信息。
非常感谢任何帮助!
// Object that I want to generate types from
const PRODUCT_SECTIONS = {
fruit: {
name: "Delicious fruit",
products: {
banana: "Banana",
apple: "Apple",
},
},
vegetables: {
name: "Fresh vegetables",
products: {
mixedGreens: "Mixed greens",
lettuce: "Lettuce",
cucumbers: "Cucumbers",
},
},
soda: {
name: "Quality soda",
products: {
coke: "Coke",
sprite: "Sprite",
},
},
} as const;
// Desired type 1: all section names
type SECTION_NAME = "Delicious fruit" | "Fresh vegetables" | "Quality soda";
// Desired type 2: all products
type PRODUCT = "Banana" | "Apple" | "Mixed greens" | "Lettuce" | "Cucumbers" | "Coke" | "Sprite";
// Desired type 3: product selection allowing 1 product per section
type SELECTED_PRODUCTS_STATE = {
fruit: "Banana" | "Apple";
vegetables: "Mixed greens" | "Lettuce" | "Cucumbers";
soda: "Coke" | "Sprite";
};
【问题讨论】:
-
this approach 适合您吗?如果是这样,我可以写一个答案;如果没有,请告诉我我缺少什么。
-
该死的@jcalz 你是个巫师。我什至不知道AllValuesOf,我正在尝试使用
typeof PRODUCT_SECTIONS[keyof typeof PRODUCT_SECTIONS]["products"]lmao -
谢谢@jcalz!你太棒了!这很好用。愚蠢的问题,但是当产品变成一个数组时,这个答案会如何改变呢?我很难修改你的答案以适应这个different object。
-
数组有数字索引以外的键,所以你需要像this 这样的东西。这似乎超出了这个问题的范围,对吧?我可以按要求回答原始问题吗?如果您有后续问题,您可以考虑发布一个新问题吗?这对你有用吗?
-
@Thomas 我正在写一个可以解释的答案,但请参阅the documentation for distributive conditional types。
标签: javascript typescript object types tsc