Is there a way to dynamically infer types, similar to a union type?
I am trying to register multiple elements from different parts of the code using a method like registerElement(...)
, but I am struggling with inferring these new types in TypeScript. This leads to errors like
Type '"pack"' is not assignable to type '"common"'
.
In the desired behavior, I expect that when a new element is registered, such as "pack"
, it becomes available for use. Since I do not know how many elements there will be and they can be added or removed with new code, I do not want to hard code types like:
type ElementTypes = Common | Pack | ...N
I understand that TypeScript infers types at compile-time, not runtime, and the example below does not work.
interface BaseElement<T, C> {
name: T,
nested: C[]
}
interface Common extends BaseElement<'common', string> {}
const common: Common = {
name: 'common',
nested: []
}
const myElements = {common}
type ElementTypes = keyof typeof myElements
const foo: ElementTypes = 'common'; // Ok.
// Assign a new element
interface Pack extends BaseElement<'pack', Common> {}
const pack: Pack = {
name: 'pack',
nested: []
}
Object.assign(myElements, {pack});
const bar: ElementTypes = 'pack'; // Not working.