Neo
Neo

Reputation: 4760

Dynamic return of a variable based on the argument

So I have n imports

import icon1 from './icons/icon1.svg';
import icon2 from './icons/icon2.svg';
// 100+ more imports

I want to write a function that returns correpsonding icon based on the icon name

export const getIcon: GetIcon = (iconName) => {
    switch (iconName) {
        case 'icon1': return icon1;
        case 'icon2': return icon2;
        // more returns
    }
 }

how do i do it without using switch case ?

In javascript I used to

export icon1 from './icons/icon1.svg';
export icon2 from './icons/icon2.svg';
// More icons

and in the second file

import * as icons from './icons';
export const getIcon = (iconName) => icons[iconName]

So I didn't have to write big switch statement to map the imports to the value. How can I simplify in typescript?

Upvotes: 1

Views: 347

Answers (2)

ford04
ford04

Reputation: 74500

Given ES namespace import, you can get the typed keys "icon1" | "icon1" of the iconsnamespace:

import * as icons from './icons';

type IconKeys = keyof typeof icons;

Just restrict the iconName argument type of function getIcon to be one of the icon keys. Now iconName can be used as a computed property name to get the wanted icon.

export const getIcon = (iconName: IconKeys) => icons[iconName];

// or without explicit type
export const getIcon = (iconName: keyof typeof icons) => icons[iconName];

Upvotes: 1

Fyodor Yemelyanenko
Fyodor Yemelyanenko

Reputation: 11848

In TS you can do very similar to JS.

  1. In Icons file

    import icon1 from "./icon1";
    import icon2 from "./icon2";
    
    const icons = [icon1, icon2];  // type is string[]
    export = icons;
    
  2. In second file

    import icons from './icons';
    
    export const getIcon = (icon: number) => icons[icon];   // type of getIcon is (icon: number): string
    

You can also look at this answer with some addition details and ideas.

Upvotes: 0

Related Questions