I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature".
Despite extensive discussions on Typescript's GitHub pages, I have yet to find a solution for my specific case. I've tried using enums and unions, but the error persists.
For example with enums (playground)
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])
})
Alternatively, consider the example with unions (playground)
type Names = 'joe' | 'bill' | 'bob'
type ContactList = {
[K in Names]: {
isFriend: boolean;
}
}
const contactList: ContactList = {
joe: {
isFriend: true,
},
bill: {
isFriend: false,
},
bob: {
isFriend: true,
},
};
Object.keys(contactList).forEach(name => {
// turn on 'noImplicitAny' and get error
console.log(contactList[name])
})
In both cases, I am specifying to TypeScript that only keys from Names are allowed in the object, and since [key in Names]
should be an index signature, I'm puzzled by the error message. Apologies if this is a beginner question, as I am still relatively new to TypeScript. Thank you.