So, I initially wanted to do the following conversion:
import { ComponentType } from 'react';
import { Component1, Component2 } from './components';
const components = {
foo: Component1,
bar: Component2,
};
// Into
const componentLookup = {
foo: {
name: 'foo',
component: Component1
},
bar: {
name: 'bar',
component: Component2
},
};
So, I created the following TS logic:
const components = {
foo: Component1,
bar: Component2,
};
type ComponentName = keyof typeof components;
type ComponentLookup = {
[key in ComponentName]: {
name: ComponentName;
component: ComponentType;
};
};
let componentLookup: ComponentLookup = {} as ComponentLookup;
(Object.keys(components) as ComponentName[]).forEach((name) => {
componentLookup[name] = { name: name, component: components[name] };
});
// Intellisense picks up keys
componentLookup.foo;
componentLookup.bar;
Finally, I decided I want to create a function createLookups
to take the components object and perform the logic instead, however, intellisense is having trouble.
const createLookups = (components: {
[name: string]: ComponentType;
}): {
[key in keyof typeof components]: {
name: keyof typeof components;
component: ComponentType;
};
} => {
type ComponentName = keyof typeof components;
type ComponentLookup = {
[key in ComponentName]: {
name: ComponentName;
component: ComponentType;
};
};
let componentLookup: ComponentLookup = {} as ComponentLookup;
(Object.keys(components) as ComponentName[]).forEach((name) => {
componentLookup[name] = { name: name, component: components[name] };
});
return componentLookup;
};
If createLookups
is defined in the same file and I call createLookups(components)
, intellisense picks up on foo
and bar
; however, if createLookups
is defined in another file, it does not pick up on the foo
/bar
keys readily.
Is this an issue with TypeScript or my editor (WebStorm)?