Angular Enum Type

Discussão em 'Angular' iniciado por Travis Heeter, Junho 11, 2025.

  1. I have urls defined like this:

    E_one = '/url1/'
    E_two = '/url2/'
    E_three = '/url3/'

    export LINKS = { E_one: E_one, E_two: E_two, E_three: E_three}


    So I import 'LINKS', but then I want to dynamically navigate like this:

    this.router.navigate([LINKS[`E_${variable}`]])


    But I get a type error:


    Element implicitly has an 'any' type because expression of type 'E_${string}' can't be used to index type '{ E_one: string, E_two: string, E_three:string};
    ​

    So I try to cast it as one of those three

    export enum LinkType {'E_one','E_two','E_three'}

    this.router.navigate([LINKS[`E_${variable}` as LinkType]])


    But that doesn't work. "LinkType can't be used to index type '{E_one..."

    But if I do this it does work

    this.router.navigate([LINKS[`E_${variable}` as 'E_one'|'E_two'|'E_three']])


    What am I doing wrong with Enums? Also, if you know of a more elegant way to do this, that would be great.

    Continue reading...

Compartilhe esta Página