英文:
How to get union of value types of a nested object?
问题
以下是代码的翻译部分:
给定这样的对象:
```ts
const deepNestedObject = {
a: "value",
b: {
c: "nestedvalue",
d: {
e: "deepNestedValue"
}
}
}
如何生成一个联合类型,仅限于边缘的非对象值
type EdgeValueUnion = DeepValueOf<typeof deepNestedObject>; // 应该等同于 "value" | "nestedValue" | "deepNestedValue"
到目前为止,我尝试过这个:
type ValueOf<T> = T[keyof T];
type DeepValueOf<
T extends Record<string, unknown>,
Key = keyof T
> = Key extends string
? T[Key] extends Record<string, unknown>
? DeepValueOf<T[Key]>
: ValueOf<T>
: never;
但它还不太对,因为它仍然允许树中的对象值通过。例如:
const edgeValue: EdgeValueUnion = deepNestedObject.b;
<details>
<summary>英文:</summary>
Given an object like this:
```ts
const deepNestedObject = {
a: "value",
b: {
c: "nestedvalue"
d: {
e: "deepNestedValue"
}
}
}
How do I generate a union type of specifically only the non-object values at the edge
type EdgeValueUnion = DeepValueOf<typeof deepNestedObject>; // Should equate to "value" | "nestedValue" | "deepNestedValue"
So far I've tried this:
type ValueOf<T> = T[keyof T];
type DeepValueOf<
T extends Record<string, unknown>,
Key = keyof T
> = Key extends string
? T[Key] extends Record<string, unknown>
? DeepValueOf<T[Key]>
: ValueOf<T>
: never;
but it's not quite right because it still allows object values in the tree to pass. e.g.
const edgeValue: EdgeValueUnion = deepNestedObject.b;
答案1
得分: 1
从值中提取所有字符串:
type EdgeValueUnion = Extract<DeepValueOf<typeof deepNestedObject>, string>;
还需要使用 const 断言来确保这些字符串被推断为字面量,而不是通用的 string
类型:
const deepNestedObject = {
a: "value",
b: {
c: "nestedvalue",
d: {
e: "deepNestedValue",
},
},
} as const;
英文:
Extract all the strings from the values:
type EdgeValueUnion = Extract<DeepValueOf<typeof deepNestedObject>, string>;
You also need a const assertion to make sure the strings are inferred as literals instead of the general string
type:
const deepNestedObject = {
a: "value",
b: {
c: "nestedvalue",
d: {
e: "deepNestedValue",
},
},
} as const;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论