How to get around property does not exist on 'Object'

后端 未结 2 464
梦谈多话
梦谈多话 2020-12-05 09:36

I\'m new to Typescript, and not sure how to word this question.

I need to access two \"possible\" properties on an object that is passed in the constructor. I know

相关标签:
2条回答
  • 2020-12-05 09:55

    If you use the any type instead of Object, you can access any property without compile errors.

    However, I would advise to create an interface that marks the possible properties for that object:

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

    Since all of the fields use ?:, it means that they might or might not be there. So this works:

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

    If something comes from javascript, you can do something like this:

    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
    

    Of course this solution only works as expected if you are only unsure about the presence of a property not of it's type.

    0 讨论(0)
  • 2020-12-05 10:08

    If you don't want to change the type or create an interface, you can also use this syntax to access unknown properties:

    selector ():string {
        return this.options["selector"];
    }   
    
    template ():string {
        return this.options["template"];
    }
    
    0 讨论(0)
提交回复
热议问题