是否可以递归地从 Typescript 中的键对象获得强类型?
这是我拥有的示例代码。
const test = {
name: 'abc',
author: {
email: 'abc@example.com',
url: 'http://example.com/'
}
}
type AType = keyof typeof test
type AObjectKeyToValue = {
[K in AType]: K // <- K is just the keys!
}
然后我想创建使用AObjectKeyToValue
类型的新变量,以便我可以从中获得电源自动完成。
const b: AObjectKeyToValue
b.
▾▾▾
name
author
如您所见,我的自动完成完全符合我的需要。但是当我需要从孩子那里自动完成时,我的问题就来author
了。
const b: AObjectKeyToValue
b.author.
▾▾▾
// Just string property. Can't find `email` and `url`
如何编写好的类型,以便我在访问b.author.
时可以获取email
和url
密钥?
我们可以从一个值(在编译时确定(创建一个类型,并将其用于其他值:
let b: typeof test = ...;
b.author.email // will be of type "string"