【问题标题】:How to get around property does not exist on 'Object'“对象”上不存在如何绕过属性
【发布时间】:2016-04-13 19:36:29
【问题描述】:

我是 Typescript 的新手,不知道如何表达这个问题。

我需要访问构造函数中传递的对象的两个“可能”属性。我知道我错过了一些检查以查看它们是否已定义,但 Typescript 向我抛出“'对象'上不存在属性”消息。该消息出现在 selectortemplate 返回。

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 {

   }   
}

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

【问题讨论】:

    标签: object typescript


    【解决方案1】:

    如果您使用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
    

    当然,此解决方案仅在您不确定是否存在非其类型的属性时才能按预期工作。

    【讨论】:

    • 嗨,很好的答案。为什么你不使用类而不是接口?
    • @RafaelReyes 接口在生成的 javascript 中没有任何痕迹,它纯粹是类型信息(在这种情况下应该如此)。
    【解决方案2】:

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

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

    【讨论】:

    • 这可行,但似乎真正破坏了 TypeScript 的打字
    • 当您执行 for (let item of items) 并且 item.x 不是对象的属性并且您似乎无法强制转换时,这会更加棘手。
    猜你喜欢
    • 1970-01-01
    • 2021-08-11
    • 2020-08-27
    • 1970-01-01
    • 2014-09-10
    • 2019-10-11
    • 2018-02-10
    • 2018-03-03
    • 1970-01-01
    相关资源
    最近更新 更多