Object 在';上不存在如何绕过酒店的问题;对象';
我是打字新手,不知道这个问题该怎么说 我需要访问构造函数中传递的对象上的两个“可能”属性。我知道我错过了一些检查,看看它们是否已定义,但Typescript向我抛出了一条“对象上不存在属性”消息。该消息出现在选择器上,并且模板返回Object 在';上不存在如何绕过酒店的问题;对象';,object,typescript,Object,Typescript,我是打字新手,不知道这个问题该怎么说 我需要访问构造函数中传递的对象上的两个“可能”属性。我知道我错过了一些检查,看看它们是否已定义,但Typescript向我抛出了一条“对象上不存在属性”消息。该消息出现在选择器上,并且模板返回 class View { public options:Object = {}; constructor(options:Object) { this.options = options; } selector ():str
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"];
}
嗨,回答得好。为什么不使用类而不是接口?@RafaelReyes Interfaces在生成的javascript中没有任何跟踪,这纯粹是类型信息(在本例中应该是这样的)。这很有效,但似乎确实破坏了TypeScript的类型。当您执行for(let items of items)时,这更为棘手而且item.x不是object的属性,您似乎无法强制转换它。