Reputation: 655
Typescript is raising the error "Element implicitly has an 'any' type because type 'HumansToDogs' has no index signature."
on the following code.
Everything seems explicit and straightforward to me, can anyone help?
type HumanName = 'Jessie' | 'Mark';
type DogName = 'Spot' | 'Buddy';
type HumansToDogs = {
[key in HumanName]: DogName; // Isn't this an index signature?
}
const humansToDogs: HumansToDogs = {
'Jessie': 'Buddy',
'Mark': 'Spot',
};
for (const human in humansToDogs) {
const dog = humansToDogs[human]; // Index signature error here
}
Upvotes: 2
Views: 94
Reputation: 1485
You can explicitly let the Typescript compiler know that human
referes to a key of HumanName
as follows:
humansToDogs[human as keyof HumanName]
But a better way is to define the shape of your data, you can explicitly define a new type that declares the index as a string:
type HumanNames = {[k: string] HumanName};
Upvotes: 0
Reputation: 249506
The for..of
will type the loop variable as string
. With noImplicitAny
you can't index into a type with an arbitrary string
. The simplest solution is to use a type assertion:
for (const human in humansToDogs) {
const dog = humansToDogs[human as HumanName]; // Index signature error here
}
Upvotes: 2