De *_* As 30 methods properties typescript
我在TypeScript中输入了一个拼写错误,这是在代码审查期间被选中的.
我用someArray.indexOf[someObject]而不是someArray.indexOf(someObject).
我希望IDE /编译器出错.相反,没有引发错误,结果只是未定义.
有谁能解释一下?
sja*_*han 34
很容易.
someArray.indexOf你知道这是一个function,它也是一个对象,可以有属性.
通过这样做someArray.indexOf[someObject],您尝试使用值为值的键到达属性someObject.
当然,它没有在indexOf函数上定义,所以它返回undefined.
快速示例说明了语法和函数可以具有属性的事实;):
const array = [];
array.indexOf['anyValue'] = 'test';
console.log(array.indexOf.anyValue);Run Code Online (Sandbox Code Playgroud)
编辑
这是尝试问题的TypeScript方面的答案.
如您所知,TypeScript旨在与JavaScript兼容.因此,与JS一样,您可以通过以下方式访问对象的属性:
obj.propertyobj['property']当然,通过使用"静态"方式访问属性,TypeScript将引发错误!
但是通过动态访问属性的方式,TypeScript编译器无法确定它的类型或是否存在,因为在运行TypeScript之后,将在运行时计算括号之间的值.
这就是为什么它会被隐含地标记为any.
正如David Sherret在他的回答中提到的那样,你可以通过添加标志来强制TypeScript引发错误--noImplicitAny,请参阅他的回答以获取更多有关此内容的详细信息!
希望这有帮助;)
array.indexOf 是一个功能.
功能是对象.
您正在访问someObject该array.indexOf功能的属性.
你会得到的undefined.
const array = [1, 2, 3]
const someObject = 'asdasd'
console.log(array.indexOf[someObject])
// undefinedRun Code Online (Sandbox Code Playgroud)