英文:
Get union of values in for object
问题
I can help with that. Here's the translation of your provided content:
我尝试编写一个函数的类型,该函数接受任何结构的记录并将值转换为一个可辨识联合类型。所以类似以下的东西:
const getKeys = <T extends { key: string }>(items: T[]): T['key'] => {
// ...
}
// keys 应该具有类型 "foo" | "bar"
// 实际上具有 string 类型
const keys = getKeys([{ key: "foo" }, { key: "bar" }])
// keys2 应该具有类型 "baz" | "qux"
// 实际上具有 string 类型
const keys2 = getKeys([{ key: "foo" }, { key: "qux" }])
然而,keys
和 keys2
实际上具有 string
类型。
理想情况下,您可以获得类似以下的良好 API,使用记录的工作示例:
const getKeys = <T extends string>(items: T[]): T => {
// ...
}
// keys 具有类型 "foo" | "bar"
const keys = getKeys(["foo", "bar"])
// keys2 具有类型 "baz" | "qux"
const keys2 = getKeys(["baz", "qux"])
如何实现这个?要求不能在参数上使用 as const
。
英文:
I'm trying to write the types for a function that accepts records of any structure and transforms the values into a discriminated union. So something like the following:
const getKeys = <T extends {key: string}>(items: T[]): T['key'] => {
// ...
}
// keys should have type "foo" | "bar"
// instead has type string
const keys = getKeys([{ key: "foo" }, { key: "bar" }])
// keys2 should have type "baz" | "qux"
// instead has type string
const keys2 = getKeys([{ key: "foo" }, { key: "qux" }])
However, keys
and keys2
instead has the type of string
.
Ideally, you would get the kind of nice API like the following, working example but using records:
const getKeys = <T extends string>(items: T[]): T => {
// ...
}
// keys has type "foo" | "bar"
const keys = getKeys(["foo", "bar"])
// keys2 has type "baz" | "qux"
const keys2 = getKeys(["baz", "qux"])
How can I do this?
Requirements
- Cannot use
as const
on the argument
答案1
得分: 2
The alternative to const assertion would be const type parameters introduced in Typescript 5.0.
Previously, typescript would infer a more generic type for the objects; however, const type assertions
tells the compiler to take the exact type without making it more general.
Implementation:
const getKeys = <const T extends { key: string }>(items: T[]): T['key'] => {
return {} as any
};
// keys should have type "foo" | "bar"
const keys = getKeys([{ key: 'foo' }, { key: 'bar' }]);
// keys2 "baz" | "qux"
const keys2 = getKeys([{ key: 'bar' }, { key: 'qux' }]);
英文:
The alternative to const assertion would be const type parameters introduced in Typescript 5.0.
Previously, typescript would infer a more generic type for the objects; however, const type assertions
tells the compiler to take the exact type without making it more general.
Implementation:
const getKeys = <const T extends { key: string }>(items: T[]): T['key'] => {
return {} as any
};
// keys should have type "foo" | "bar"
const keys = getKeys([{ key: 'foo' }, { key: 'bar' }]);
// keys2 "baz" | "qux"
const keys2 = getKeys([{ key: 'bar' }, { key: 'qux' }]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论