我最近開始做打字稿,我對跳過級別深度感到好奇,是否可以在打字稿中跳過深度級別?
// from
A -> B -> C
// to
A -> C
const sample = {
A: {
B: {
C: "one",
}
},
};
type Make<A, Z> = {
[B in keyof A]: {
[C in keyof A[B]]: {
[D in keyof A[B][C]]: Z;
}
};
};
function foo<T>(object: T): Make<T, number> {
return object as any;
}
// outputs: one
console.log(foo(sample).A.B.C);
如果我們想像這樣跳過一個級別怎么辦?
// expected output: one
console.log(foo(sample).A.C);
我試圖這樣做,但沒有奏效
type Make2<A, Z> = {
[B in keyof A]: {
[D in keyof A[B][]]: Z;
};
};
function foo2<T>(object: T): Make2<T, number> {
return object as any;
}
// doesnt work
console.log(foo2(sample).A.C);
uj5u.com熱心網友回復:
您可以通過使用鍵重新映射和條件輸入來簡單地跳過中間層。
我們使用重映射訪問器 in 遍歷物件的值[K in keyof T],檢查其子T[K]物件是否為物件,如果是,則回傳 , 的推斷子物件T[K],Item否則僅回傳T[K]
type SkipFirstDepth<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends Record<string, infer Item> ? Item : T[K];
};
type Make = SkipFirstDepth<typeof sample>
然后它的輸入將是
{
A: {
C: string;
};
}
或者,如果您想一直向下跳過所有其他層,則必須使用遞回型別。
type SkipEveryOtherDepth<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends Record<string, infer Item>
? Item extends Record<string, any>
? SkipEveryOtherDepth<Item>
: Item
: T[K];
};
type Example = SkipEveryOtherDepth<{
foo: {
bar: {
foo: {
bar: {
foo: 'bar';
};
};
};
};
}>;
那么最終的型別將是
{
foo: {
foo: {
foo: 'bar';
};
};
}
I did this off the cuff, so it may not work in every object shape but definetly works in these given examples.
Check these examples in action at the playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445945.html
上一篇:元組與硬編碼字串
