Search code examples
typescripttyping

typescript declare type as a property of class


class Icons{
    static home = "<svg...";
    static back = "ico/back.png";
}

class Menu{
    addItem(icon: ????){....}
}

What type would you declare in the icon parm of Menu.addItem to force it to be a member of class Icons?

So far

addItem(icon:[keyof typeof Icons]);
menu.addItem("home", someFn);

approximates and validates using the property names as strings but, is it possible declare it a type that would let me express the direct reference to the property of Icons

menu.addItem(Icons.home, someFn);

I suspect I am missing something quite elemental here


Solution

  • Use a string enum:

    enum Icons {
        home = "<svg...",
        back = "ico/back.png"
    }
    
    function addItem(icon: Icons) {
        console.log(icon);
    }
    
    addItem(Icons.home);