Mur*_*NER 22 javascript typescript uri.js
我正在尝试打字稿可选链接运算符,但抛出了这个异常。
index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access.
Run Code Online (Sandbox Code Playgroud)
我的示例代码如下
const url = URI({
protocol: 'http',
hostname: 'example.org'
})
// This line throwed
document.getElementById('output')?.innerHTML = url.toString()
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
iam*_*gga 27
const output = document.getElementById('output');
if (output) output.innerHTML = url.toString()
Run Code Online (Sandbox Code Playgroud)
此运算符用于访问深嵌套值。
我们来看看document.getElementById('output')?.innerHTML。这将返回undefined(如果 '#output' 不存在)或string(如果 '#output' 存在)。而你试图分配string给它。
在这里,您尝试为可能不存在的对象属性设置新值。
所以是的,在赋值的左侧不能使用可选的属性访问。
您可以在提案中阅读更多相关信息
Nit*_*Jha 18
objectVariableName!.propertyName = 'some value to assign';
Run Code Online (Sandbox Code Playgroud)
请注意感叹号,即!
| 归档时间: |
|
| 查看次数: |
32877 次 |
| 最近记录: |