我用了一个模块可以做这样的事情
function print(obj, key) {
console.log(obj[key])
}
print({'test': 'content'}, '/* vs code will show code recommendation when typing */')
我想要这个功能,但我忘记了模块的名称,我什至不确定我是否记错了(也许这是不可能的)。
我正在处理一个包并且有这样的代码:
interface Box {
content: {
[key: string]: string
}
using: string // key of content
}
const box: Box = {
content: {
'something': 'inside'
},
using: 'something'
}
function showBox(box: Box) {
console.log(box.content[box.using])
}
实际上content
是一个对象来自另一个使用打字稿的包。如果可能,我不想包装类型。
为了帮助开发人员在编码过程中发现错误,我正在寻找是否有办法检查无效Box
类型,例如:
const box: Box = {
content: {
'something': 'inside'
},
using: 'samething' // raise error when checking type
}
或者任何方式都可以让IDE的代码推荐知道using
应该是content
对象的键。
我的代码目前看起来像这样,但这不是我想要的,我不知道要继续
interface Box {
content: {
[key: string]: string
}
using: keyof Box['content'] // will be string | number
}
感谢所有回复
您的解决方案实际上是正确的,但 IDE 无法为您提供任何建议,因为它keyof Box['content']
被输入为任意字符串。如果你知道它content
应该总是有一些特定的结构,你可以Box
像这样把它放在描述中:
interface Box {
content: {
something: string;
};
// now it only allowed to be 'something', and IDE will suggest it
using: keyof Box['content'];
}
如果你content
的类型实际上是一个参数(意味着你可以有任意类型的框),你应该让它成为Box
接口的参数,从而使它成为一个通用接口:
interface GenericBox<T> {
content: T;
using: keyof T;
}
现在你可以像这样使用它:
// simple example interface to fill a box
interface TestContent {
x: string;
y: number;
}
const genericBox: GenericBox<TestContent> = {
content: {x: '', y: 0},
using: 'x', // now it can be only 'x' or 'y', and IDE will suggest it
};
在操场上看看。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句