2

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
}

2 Answers 2

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.