Note: I have updated the question to hopefully make things clearer.
I am trying to instantiate classes through a proxy object called elemTypes
. This object is a list of references to classes that I want to use to programmatically build objects based on a DOM-like tree structure. I am very new to TypeScript, so I'm hoping that I am just missing something simple here?
Here is the code:
type elemDef = {
type: string,
name: string,
childNodes: object[]
}
class Elem {
childNodes: object[]
constructor (childNodes: object[]) {
this.childNodes = childNodes
}
}
class Div extends Elem {
constructor (childNodes: object[]) {
super(childNodes)
}
}
class Form extends Elem {
constructor (childNodes: object[]) {
super(childNodes)
}
}
class Input extends Elem {
name: string
constructor (childNodes: object[], nodeDef: elemDef) {
super(childNodes)
this.name = nodeDef.name
}
}
const div = {
type: 'Div',
childNodes: [
{
type: 'Form',
childNodes: [
{
type: 'Input',
name: 'username',
childNodes: []
},
{
type: 'Input',
name: 'password',
childNodes: []
},
]
}
]
}
// I expect that I am doing this part wrong:
const elemTypes = {
Div,
Form,
Input
}
const makeElem = (nodeDef: elemDef) => {
const childNodes:object[] = []
nodeDef.childNodes.forEach((childNodeDef: object): void => {
const element = new elemTypes[childNodeDef.type](childNodeDef)
childNodes.push(element)
})
const element = new elemTypes[nodeDef.type](nodeDef)
return element
}
// This line just demonstrates that the code is working:
console.log(JSON.stringify(makeElem(div), null, 2))
The output of the line above is:
{
"childNodes": {
"type": "Div",
"childNodes": [
{
"type": "Form",
"childNodes": [
{
"type": "Input",
"name": "username",
"childNodes": []
},
{
"type": "Input",
"name": "password",
"childNodes": []
}
]
}
]
}
}
The issue I am having, is that SublimeText 3 is giving me this error:
Element implicity has a type 'any' type because the type
'{ Div: typeof Div; Form: typeof Form; Input: typeof Input };
has no index signature;
I have tried figuring this out by reading the TypeScript documentation and looking at some StackOverflow answers on similar questions, but I can not seem to find out what I am doing wrong here.
But does anyone know if there is a way to define the meta
object that will stop be having this implicit any error in my IDE? (Note: I do not want to turn implicit errors off in my .ts-config.js
file.)
I do not want to turn off implicit any rule in my ts-config
.
Any ideas appreciated.