Want to get around property does not exist on ‘Object’? 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:
1 2 3 4 | 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:
1 2 3 4 5 6 7 | 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:
1 2 3 4 5 6 7 | import isObject from 'lodash/isObject' const myOptions: Options = isObject(somethingFromJS) // if an object ? (<Options> somethingFromJS) // cast it : {} // else create an empty object doStuff(myOptions) // this works now |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.