【发布时间】:2023-02-09 19:27:20
【问题描述】:
我想创建一个具有通用类型和 2 个属性的类型,这些属性将拆分指定类型的嵌套路径。
export type RecursiveKeyOf<TObj extends object> = {
[TKey in keyof TObj & (string | number)]: TObj[TKey] extends any[]
? `${TKey}`
: TObj[TKey] extends object
? `${TKey}` | `${TKey}.${RecursiveKeyOf<TObj[TKey]>}`
: `${TKey}`;
}[keyof TObj & (string | number)];
type SubRecursiveKeys<RK extends string, PFX extends RK> = RK extends `${PFX}.${infer SubKey}` ? SubKey : never;
const a = {
level1: {
level2: {
level3: {
level4: {
level5: 'test'
}
}
}
}
}
type SubKeys = SubRecursiveKeys<RecursiveKeyOf<typeof a>, 'level1.level2'> // ok
// error here - does not satisfy the constraint
type ShortHandKeyMapper<F extends object, Base extends RecursiveKeyOf<F> = RecursiveKeyOf<F>> = {
control: Base // error here - does not satisfy the constraint
value: SubRecursiveKeys<RecursiveKeyOf<F>, Base>
}
const denyMapper: ShortHandKeyMapper<typeof a> = {
control: 'level1.level2.level3',
value: 'level2' // shouldnt allow this
}
const okMapper: ShortHandKeyMapper<typeof a> = {
control: 'level1.level2.level3',
value: 'level4' // should allow this or 'level4.level5'
}
ShortHandKeyMapper 是将 control 作为嵌套路径的前缀部分和 value 作为其余部分的类型。
我收到 does not satisfy the constraint,这毫无意义。
【问题讨论】:
标签: typescript generics typescript-generics