我是Typescript的新手,不知道该如何表达这个问题。
我需要访问在构造函数中传递的对象的两个"可能"属性。我知道我错过了一些检查,看看它们是否已定义,但Typescript向我抛出了一条"Property not exists on'Object'"消息。消息出现在选择器上,模板返回。
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对我来说是新的。
如果使用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
当然,只有当您不确定某个属性(而不是其类型)的存在时,此解决方案才能按预期工作。
如果您不想更改类型或创建接口,也可以使用此语法访问未知属性:
selector ():string {
return this.options["selector"];
}
template ():string {
return this.options["template"];
}