Digamos que estoy importando algunos objetos que tienen el mismo método. ¿Cómo puedo hacer referencia a ellos dinámicamente, por ejemplo, por cadenas?
Por ejemplo,
import { Foo } from 'path/to/foo'; import { Bar } from 'path/to/bar'; import { Baz } from 'path/to/baz'; const things = ['Foo', 'Bar', 'Baz']; things.forEach(thing => { thing.doSomething(); });Si tiene que ser cadenas, puedes hacer esto:
import { Foo } from 'path/to/foo'; import { Bar } from 'path/to/bar'; import { Baz } from 'path/to/baz'; const things = { 'Foo': Foo, 'Bar': Bar, 'Baz': Baz }; Object.keys(things).forEach(key => { things[key].doSomething(); });Si no tiene que ser cadenas, simplemente puede crear una matriz de sus Objetos importados
import { Foo } from 'path/to/foo'; import { Bar } from 'path/to/bar'; import { Baz } from 'path/to/baz'; const things = [Foo, Bar, Baz]; things.forEach(thing => { thing.doSomething(); });Simplemente no use string , utilícelo como lo ha importado así:
import { Foo } from 'path/to/foo'; import { Bar } from 'path/to/bar'; import { Baz } from 'path/to/baz'; const things = [Foo, Bar, Baz]; things.forEach(thing => { thing.doSomething(); });