注意:我已经更新了这个问题,希望能让事情更清楚。
我正在尝试通过一个名为elemTypes
. 此对象是对类的引用列表,我想使用这些类以编程方式构建基于类似 DOM 的树结构的对象。我对 TypeScript 很陌生,所以我希望我在这里遗漏了一些简单的东西?
这是代码:
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))
上面一行的输出是:
{
"childNodes": {
"type": "Div",
"childNodes": [
{
"type": "Form",
"childNodes": [
{
"type": "Input",
"name": "username",
"childNodes": []
},
{
"type": "Input",
"name": "password",
"childNodes": []
}
]
}
]
}
}
我遇到的问题是 SublimeText 3 给了我这个错误:
Element implicity has a type 'any' type because the type
'{ Div: typeof Div; Form: typeof Form; Input: typeof Input };
has no index signature;
我已经尝试通过阅读 TypeScript 文档并查看一些 StackOverflow 关于类似问题的答案来解决这个问题,但我似乎无法找出我在这里做错了什么。
但是有谁知道是否有一种方法可以定义meta
将停止在我的 IDE 中出现这种隐含任何错误的对象?(注意:我不想在我的.ts-config.js
文件中关闭隐式错误。)
我不想在我的ts-config
.
任何想法表示赞赏。