代码之家  ›  专栏  ›  技术社区  ›  Eric Harms

如何绕过“Object”上不存在的属性

  •  72
  • Eric Harms  · 技术社区  · 10 年前

    我是打字新手,不知道该如何用词回答这个问题。

    我需要访问构造函数中传递的对象的两个“可能”属性。我知道我错过了一些检查,看看它们是否已定义,但Typescript正在向我发送一条“Property does not exist on'Object'”消息。消息显示在 选择器 样板 返回。

    class View {
        public options:Object = {};
    
       constructor(options:Object) {
           this.options = options;
       }
    
       selector ():string {
           return this.options.selector;
       }   
    
       template ():string {
           return this.options.template;
       }   
    
       render ():void {
    
       }   
    }
    

    我相信它相当简单,但打字对我来说是新的。

    2 回复  |  直到 9 年前
        1
  •  89
  •   Balázs Édes    6 年前

    如果您使用 any 键入而不是 Object ,您可以访问任何属性而不会出现编译错误。

    但是,我建议创建一个接口来标记该对象的可能属性:

    interface Options {
      selector?: string
      template?: string
    }
    

    由于所有字段都使用 ?: 这意味着他们可能在那里,也可能不在那里。所以这是有效的:

    function doStuff(o: Options) {
      //...
    }
    
    doStuff({}) // empty object
    doStuff({ selector: "foo" }) // just one of the possible properties
    doStuff({ selector: "foo", template: "bar" }) // all props
    

    如果有些东西来自javascript,你可以这样做:

    import isObject from 'lodash/isObject'
    
    const myOptions: Options = isObject(somethingFromJS) // if an object
        ? (somethingFromJS as Options) // cast it
        : {} // else create an empty object
    
    doStuff(myOptions) // this works now
    

    当然,只有当您不确定某个属性(而不是其类型)的存在时,此解决方案才能按预期工作。

        2
  •  19
  •   John Montgomery    9 年前

    如果不想更改类型或创建接口,也可以使用此语法访问未知属性:

    selector ():string {
        return this.options["selector"];
    }   
    
    template ():string {
        return this.options["template"];
    }
    
    推荐文章