Home > Software engineering >  Typescript - How to solve - Element implicitly has an 'any' type because expression of typ
Typescript - How to solve - Element implicitly has an 'any' type because expression of typ

Time:01-21

I'm having trouble declaring a variable correctly.

tabs = {
 landingPage: {
  id: "landingPage",
  heading: "shop.landingPage",
  active: false,
  loaded: true,
 }}

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!

CodePudding user response:

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

CodePudding user response:

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

  • Related