Javascript 打字稿使用 [' '] 语法访问动态属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43740513/
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-08-23 02:08:00  来源:igfitidea点击:

Typescript access dynamic property with [' '] syntax

javascripttypescript

提问by Harry

export class Foo{
 someproperty: string;
}

I am trying to understand why, when trying to access dynamic object property I can do the following as I saw on one of the answers here:

我试图理解为什么,在尝试访问动态对象属性时,我可以按照我在此处的其中一个答案中看到的那样执行以下操作:

let fooObj: foo = someObj['someproperty']; 

but by doing this, I get an error.

但是通过这样做,我得到了一个错误。

let fooObj: foo = someObj.someproperty;

I am trying to understand, why the first method works for accessing/assigning to dynamic objects.

我试图理解,为什么第一种方法适用于访问/分配给动态对象。

Error:

错误:

"someproperty does not exist on type"

"someproperty does not exist on type"

Question asked before here, answer by Angelo R is the one I am interested in.

在这里之前问过的问题,Angelo R 的回答是我感兴趣的。

question

采纳答案by Asad Saeeduddin

This is just a convention in TypeScript, available for convenience. If you want to access some arbitrary property that is not defined in the type signature of the object, you can use the ["foo"]notation, and the type checker will not try to enforce that the instance you're accessing has such a property in its type signature.

这只是 TypeScript 中的一个约定,为方便起见。如果您想访问一些未在对象的类型签名中定义的任意属性,您可以使用["foo"]表示法,并且类型检查器不会试图强制您正在访问的实例在其类型签名中具有这样的属性.