Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

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

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 im missing some checks to see if they are defined, but Typescript is throwing me a "Property does not exist on 'Object'" message. The message appears on the selector and template returns.

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 {

   }   
}

I'm sure its fairly simple, but Typescript is new to me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...