代码之家  ›  专栏  ›  技术社区  ›  Ilijanovic

无法在带有typescript的对象中设置属性

  •  0
  • Ilijanovic  · 技术社区  · 4 年前
    export function collectAttributes(element: Element): AttributesInterface {
        return Array.from(element.attributes, ({ name, value }) => [
            name,
            value,
        ]).reduce((a, [key, val]) => {
            if (key.includes("@")) {
                let handlerName = key.replace("@", "")
                a.handlers.push([handlerName, val])
            } else if (key.startsWith("s:")) {
                let styleProp = key.replace("s:", "")
                a.bindedStyle.push([styleProp, val])
            } else if (key.startsWith("c:")) {
                let classProp = key.replace("c:", "");
                a.bindedClasses.push([classProp, val])
            } else if (key.startsWith("a:")) {
                let attributeProp = key.replace("a:", "");
                a.bindedAttr.push([attributeProp, val])
            } else if (key === "if") {
                a.show = val
            } else if (key.startsWith("p:")) {
                let prop = key.replace("p:", "");
                a.props[prop] = val  // <------ HERE
            } else {
                a.attr.push([key, val])
            }
            return a
        }, {
            attr: [],
            handlers: [],
            bindedStyle: [],
            bindedAttr: [],
            bindedClasses: [],
            show: null,
            visible: true,
            props: {},
            parent: element.parentElement,
            index: element.parentElement ? Array.prototype.indexOf.call(element.parentElement.children, element) : 0
        })
    }
    export interface AttributesInterface {
        attr: string[][],
        handlers: string[][],
        bindedStyle: string[][],
        bindedAttr: string[][]
        bindedClasses: string[][],
        show: string,
        visible: Boolean,
        parent: HTMLElement,
        index: number,
        props: { [key: string]: string }
    }
    

    我有一个问题,我不能设置一个新的属性。我已经试过了 { [key: string]: string } 对我的道具来说,这是一个目标,但它似乎无法解决问题。我仍然得到了错误:

    元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型“{}”。 在类型{}上找不到具有“string”类型参数的索引签名。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Ilijanovic    4 年前

    我已经修好了:

    我已将AttributesInterface添加到reduce函数的累加器中

    .reduce((a: AttributesInterface, [key, val]) => {