typescript 如何绕过“对象”上不存在的财产

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36607979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:03:42  来源:igfitidea点击:

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

objecttypescript

提问by Eric Harms

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 selectorand templatereturns.

我需要访问构造函数中传递的对象上的两个“可能”属性。我知道我错过了一些检查以查看它们是否已定义,但是 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 {

   }   
}

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

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

回答by Balázs édes

If you use the anytype instead of Object, you can access any property without compile errors.

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

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:

如果某些东西来自 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

Of course this solution only works as expected if you are only unsure about the presence of a property not of it's type.

当然,如果您只是不确定是否存在非其类型的属性,则此解决方案仅按预期工作。

回答by John Montgomery

If you don't want to change the type or create an interface, you can also use this syntax to access unknown properties:

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

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

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