Problem:
When developing with typescript, e.g. with Angular5, you get an error message similar to this one:
error TS2339: Property 'userLanguage' does not exist on type 'Navigator'.
or
error TS2339: Property 'browserLanguage' does not exist on type 'Navigator'.
Solution:
Check the error message for the correct file and line. Look for a statement like
- window.navigator.userLanguage
- window.navigator.browserLanguage
Currently typescript does not have userLanguage / browserLanguage
as a property (tested with typescript up to 2.9.2).
You can work around this by simply replacing the statement listed above by
- window.navigator['userLanguage']
- window.navigator['browserLanguage']
Using this approach, Typescript will simply not check if the attribute is present or not.
额外福利:
各浏览器对 navigator 对象中几个与语言相关的属性(language、userLanguage、browserLanguage、 systemLanguage)的返回值存在很大的差异。
navigator 对象包含有关浏览器的信息。没有应用于 navigator 对象的公开标准,不过所有浏览器都支持该对象。但是其内部一些属性及其返回值在各浏览器并不统一。
- language:返回当前的浏览器语言(来自 Mozilla Developer Center)
- userLanguage:返回操作系统设定的自然语言(来自 MSDN)
- browserLanguage:返回当前的浏览器语言(来自 MSDN)
- systemLanguage:返回当前操作系统的缺省语言(来自 MSDN)
代码中打印出了各浏览器对于这 4 个属性返回值的情况:
IE6 IE7 IE8 | Firefox Chrome Safari | Opera | |
---|---|---|---|
navigator.language | undefined | zh-CN | zh-CN |
navigator.userLanguage | zh-cn | undefined | zh-cn |
navigator.browserLanguage | zh-cn | undefined | zh-cn |
navigator.systemLanguage | zh-cn | undefined | undefined |
另外,有一篇博文对于navigator.language的详细介绍 https://www.cnblogs.com/huanghongxia/p/4234586.html