繁体   English   中英

无法使用打字稿在对象中设置属性

[英]cannot set property in object with typescript

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' 的表达式不能用于索引类型 '{}'。 在类型“{}”上找不到带有“字符串”类型参数的索引签名。

我已经修复了它:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM