1

I'm having trouble declaring a variable correctly.

I am using the code here:

ngOnInit(): void {
this.activatedRoute.fragment.subscribe(numberOfTab => {
if (numberOfTab) {
this.tabs[numberOfTab].active = true;
} else {...}

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'landingPage: { id: 'landingPage', heading: 'shop.landingPage', active: false, loaded: true }'.

No index signature with a parameter of type 'string' was found on type.

I don't quite understand why and how to fix it.

Thanks in advance for clarification!

2 Answers 2

1

Create an interface for tabs and define the tabs as a dynamic property name and assign that property to the tabs variable

interface Tabs {
  [key: string]: {
    id: string;
    heading: string;
    active: boolean;
    loaded: boolean;
  };
}

tabs: Tabs = {
  landingPage: {
    id: 'landingPage',
    heading: 'shop.landingPage',
    active: false,
    loaded: true,
  },
};
Sign up to request clarification or add additional context in comments.

Comments

0

To my simple knowledge, Typescript does not know the outcome of activatedRoute.fragment. This makes numberOfTab of type any. You then want to grab the object in tabs[numberOfTab] which basically translates to "tabs[anything]". The outcome can be anything to Typescript. And then you want to set the "active" property on that anything.

Typescript is just warning you: I don't know what tabs[numberOfTab] is.

You can solve this by explicitly stating the type of everything. For example (numberOfTab: number). Of just continue with the any type like (this.tabs[numberOfTab] as any).active = true

2 Comments

I tried to continue with any type like (this.tabs[number Of Tab] as any).active = true but still the same error occurs
(numberOfTab: any) after subscribe

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.