'对象'上不存在如何绕过属性

Eri*_*rms 54 object typescript

我是Typescript的新手,不知道怎么说这个问题.

我需要访问构造函数中传递的对象的两个"可能"属性.我知道我缺少一些检查以确定它们是否已定义,但是Typescript正在向我抛出"'对象'上不存在属性"消息.消息显示在选择器上,模板返回.

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 {

   }   
}
Run Code Online (Sandbox Code Playgroud)

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

Bal*_*des 66

如果使用any类型而不是Object,则可以访问任何属性而不会出现编译错误.

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

interface Options {
  selector?: string
  template?: string
}
Run Code Online (Sandbox Code Playgroud)

由于所有字段都使用?:,这意味着它们可能存在也可能不存在.这样可行:

function doStuff(o: Options) {
  //...
}

doStuff({}) // empty object
doStuff({ selector: "foo" }) // just one of the possible properties
doStuff({ selector: "foo", template: "bar" }) // all props
Run Code Online (Sandbox Code Playgroud)

如果某些内容来自javascript,您可以执行以下操作:

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
Run Code Online (Sandbox Code Playgroud)

当然,如果您只是不确定属性的存在而不是它的类型,那么这个解决方案只能按预期工作.

  • @RafaelReyes接口在生成的javascript中没有跟踪,它是纯粹的类型信息(在这种情况下应该是这样). (4认同)
  • 你好,很好的回答。为什么不使用类而不是接口? (2认同)

Joh*_*ery 18

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

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

template ():string {
    return this.options["template"];
}
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但似乎真的破坏了TypeScript的打字 (10认同)