tru7
tru7

Reputation: 7212

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

Upvotes: 0

Views: 99

Answers (1)

Aplet123
Aplet123

Reputation: 35482

Use a string enum:

enum Icons {
    home = "<svg...",
    back = "ico/back.png"
}

function addItem(icon: Icons) {
    console.log(icon);
}

addItem(Icons.home);

Upvotes: 1

Related Questions