[英]Retrieve nested value from nested typescript type using dotted string
是否可以使用虛線字符串檢索/更新自定義 Typescript 類型中的嵌套值?
interface IChild {
childName: string;
}
interface IRoot {
root: string;
child: IChild;
}
const O:IRoot = {
root: "Root name",
child: {
childName: "Child Name"
}
}
console.log(O['child.childname']); // Not allowed
有沒有辦法使用點符號訪問這個道具?
編輯:我把它放在一起來展示我如何使用嵌套類型中的點表示法獲取值
type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...0[]];
type Join<K, P> = K extends string | number ?
P extends string | number ?
`${K}${"" extends P ? "" : "."}${P}`
: never : never;
type NestedKeyof<T, D extends number = 10> = [D] extends [never] ? never : T extends object ?
{ [K in keyof T]-?: K extends string | number ?
`${K}` | Join<K, NestedKeyof<T[K], Prev[D]>>
: never
}[keyof T] : ""
const state: IRoot = {
name: "Root",
child: {
childname: "Child1",
grandchild: {
childname: "Child2"
}
}
} as IRoot;
const getProperty = <P extends keyof T, T>(o:T, p:P ) => {
return o[p];
}
const getNestedProperty = <P extends NestedKeyof<T,3>, T>(o:T, p:P ): any => {
const parts = String(p).split(".");
let temp: any = getProperty(o, parts[0] as keyof T);
parts.shift();
parts.map(p=> {
temp = getProperty(temp, p as keyof typeof temp);
})
return temp;
}
console.log(getNestedProperty(state, "child.grandchild.childname"));
神奇的是,當你有一個匿名類型時,你可以使用
keyof typeof anonymoustype
因此,當您遞歸結構時,您可以使用它來滿足 typescript。
首先,不允許。 屬性名稱是“childName”,您將其作為“childname”訪問。 (外殼問題)
其次,您可以使用 ts 中的點表示法訪問任何屬性。 甚至您的 IDE 也會為您輸入提示。
在這里,檢查我剛剛將您的代碼復制粘貼到這個在線 Playground for TS 並將控制台日志更改為僅點表示法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.