我有一个带有我输入的键的对象,我想循环遍历它并维护它们的类型,避免“元素隐式具有'任何'类型,因为'ContactList'没有索引签名”。
我知道 Typescript 的 GitHub 页面上对此进行了详细讨论,但我还没有找到任何解决方案来解决我在这里尝试做的事情。尝试使用枚举和联合,但我仍然收到错误。
枚举示例(游乐场)
enum Names {
Joe,
Bill,
Bob
}
type ContactList = {
[key in Names]: {
isFriend: boolean;
}
}
const contactList: ContactList = {
[Names.Joe]: {
isFriend: true,
},
[Names.Bill]: {
isFriend: false,
},
[Names.Bob]: {
isFriend: true,
},
};
Object.keys(contactList).forEach(name => {
// turn on 'noImplicitAny' and get error
console.log(contactList[name])
})
Run Code Online (Sandbox Code Playgroud)
工会示例(游乐场)
type Names = 'joe' | 'bill' | 'bob'
type ContactList = {
[K in Names]: { …Run Code Online (Sandbox Code Playgroud)