英文:
Typescript deep Pick by key without specifying a path
问题
type Form = {
collateral: {
id: "collateralField",
default: "",
deps: ["collateralToken", "borrowInput", "asd"],
severities: {
first: 'first',
second: 'second'
}
},
borrow: {
id: "borrowField",
name: "Borrow"
},
}
type IDs = DeepKeys<Form, "id">
// Expected: "collateralField" | "borrowField"
type DeepKeys<T, Q> =
T extends object
? { [K in keyof T]: (K extends Q ? T[K] : never) | DeepKeys<T[K], Q> }[keyof T]
: never;
英文:
Let's say I've this type
type Form = {
collateral: {
id: "collateralField",
default: "",
deps: ["collateralToken", "borrowInput", "asd"],
severities: {
first: 'first',
second: 'second'
}
},
borrow: {
id: "borrowField",
name: "Borrow"
},
}
I'd like to create a generic that takes the type Form
and a string Query
. It should return an union of all the values of the Queried keys.
type IDs = DeepKeys<Form, "id">
// Expected: "collateralField" | "borrowField"
This is my progress
type DeepKeys<T, Q> =
T extends object
? { [K in keyof T]: (K extends Q ? T[K] : never) | DeepKeys<T[K], Q> }[keyof T]
: never;
It seems to loop into the array object and append some unnecessary stuff.
答案1
得分: 1
你差不多搞定了。
问题在于 TypeScript 递归地迭代所有键,包括数组的键。这会在最终类型中引入不必要的键,从而造成问题。
这是一个修复:
type DeepKeys<T, Q> = T extends object
? {
[K in keyof T]: T[K] extends (infer R)[]
? never
: K extends Q
? T[K]
: DeepKeys<T[K], Q>
}[keyof T]
: never;
刚刚在 TS Playground 上测试过,似乎工作得很好。
有了这个改进的版本,你可以这样做:
type IDs = DeepKeys<Form, "id">;
英文:
You nearly got it.
The problem is that TypeScript is recurisively iterating over all keys, including those of arrays. That creates issues as there are unncecessary keys in your final type.
Here is a fix:
type DeepKeys<T, Q> = T extends object
? {
[K in keyof T]: T[K] extends (infer R)[]
? never
: K extends Q
? T[K]
: DeepKeys<T[K], Q>
}[keyof T]
: never;
Just tested this out and seemed to work fine on the TS playground.
With this improved version, you can do the following
type IDs = DeepKeys<Form, "id">;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论