如何绕过“对象"上不存在的财产 [英] How to get around property does not exist on 'Object'

查看:47
本文介绍了如何绕过“对象"上不存在的财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Typescript 的新手,不知道如何表达这个问题.

I'm new to Typescript, and not sure how to word this question.

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

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 {

   }   
}

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

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

推荐答案

如果使用 any 类型而不是 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:

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

如果某些东西来自 javascript,你可以这样做:

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.

这篇关于如何绕过“对象"上不存在的财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆