所以我想找到一种方法来拥有嵌套对象的所有键。
我有一个在参数中采用类型的泛型类型。我的目标是获取给定类型的所有键。
在这种情况下,以下代码运行良好。但是当我开始使用嵌套对象时,情况就不同了。
type SimpleObjectType = {
a: string;
b: string;
};
// works well for a simple object
type MyGenericType<T extends object> = {
keys: Array<keyof T>;
};
const test: MyGenericType<SimpleObjectType> = {
keys: ['a'];
}
Run Code Online (Sandbox Code Playgroud)
这是我想要实现的目标,但它不起作用。
type NestedObjectType = {
a: string;
b: string;
nest: {
c: string;
};
otherNest: {
c: string;
};
};
type MyGenericType<T extends object> = {
keys: Array<keyof T>;
};
// won't works => Type 'string' is not assignable to type 'a' | …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种拥有嵌套对象的所有键/值对的方法。
(用于 MongoDB 点符号键/值类型的自动完成)
interface IPerson {
name: string;
age: number;
contact: {
address: string;
visitDate: Date;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我想要实现的目标,使其成为:
type TPerson = {
name: string;
age: number;
contact: { address: string; visitDate: Date; }
"contact.address": string;
"contact.visitDate": Date;
}
Run Code Online (Sandbox Code Playgroud)
在这个答案中,我可以得到密钥Leaves<IPerson>。于是就变成了'name' | 'age' | 'contact.address' | 'contact.visitDate'。
在 @jcalz 的另一个答案中,我可以通过DeepIndex<IPerson, ...>.
是否有可能将它们组合在一起,成为类似的类型TPerson?
当我开始这个问题时,我在想它可以像这样简单[K in keyof T]: T[K];,只需进行一些巧妙的转换。但是我错了。这是我需要的:
所以界面
interface IPerson { …Run Code Online (Sandbox Code Playgroud) javascript mongodb mongodb-query typescript typescript-generics
我想创建一个简单的辅助函数来从对象中读取路径,如下所示:
interface Human {
address: {
city: {
name: string;
}
}
}
const human: Human = { address: { city: { name: "Town"}}};
getIn<Human>(human, "address.city.name"); // Returns "Town"
Run Code Online (Sandbox Code Playgroud)
这个帮助器在 JS 中很容易创建,但在 TS 中使其类型安全有点复杂。我已经做到了这一点:
type Prev = [never, 0, 1, 2, 3, 4, 5, 6, ...0[]];
type Join<K, P> = K extends string | number
? P extends string | number
? `${K}${"" extends P ? "" : "."}${P}`
: never
: never;
type Path<T, D extends number = 4> …Run Code Online (Sandbox Code Playgroud)