Skip to content

ChainedAccessUnion查找可读路径 #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jile1997 opened this issue Jan 30, 2024 · 1 comment
Open

ChainedAccessUnion查找可读路径 #5

jile1997 opened this issue Jan 30, 2024 · 1 comment

Comments

@jile1997
Copy link

ChainedAccessUnion查找可读路径,如果对象里面某个key的值为数组,会把数组的方法也当成联合类型

@kawayiLinLin
Copy link
Owner

kawayiLinLin commented Jan 31, 2024

理论上,数组的方法也是可以访问的,如果你需要移除数组的方法,再生成"可读路径"类型,可以先将数组类型转为"类数组"类型

type TransformArrayToArrayLikeDeep<T> = T extends object ? {
    [Key in keyof T]: T[Key] extends Array<any> ? {
        [ArrKey in keyof T[Key] as ArrKey extends 'length' | `${number}` ? ArrKey : never]: TransformArrayToArrayLikeDeep<T[Key][ArrKey]>
    } : TransformArrayToArrayLikeDeep<T[Key]>
} : T

然后,

interface YourObject {
    a: 1,
    b: 2,
    c: [{ d: [1] }, 2, 3]
}
// "a" | "b" | "c" | "c.length" | "c.0" | "c.1" | "c.2" | "c.0.d" | "c.0.d.length" | "c.0.d.0"
type Result = ChainedAccessUnion<TransformArrayToArrayLikeDeep<YourObject>>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants