[英]Typescript 3.7@beta Optional Chaining operator using problem
我正在嘗試 typescript 可選鏈接運算符,但拋出了這個異常。
index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access.
我的示例代碼如下
const url = URI({
protocol: 'http',
hostname: 'example.org'
})
// This line throwed
document.getElementById('output')?.innerHTML = url.toString()
如何解決這個問題?
const output = document.getElementById('output');
if (output) output.innerHTML = url.toString()
此運算符用於訪問深層嵌套值。
讓我們看一下 document.getElementById('output')?.innerHTML
。這將返回 undefined
(如果 '#output' 不存在)或string
(如果 '#output' 存在)。你試圖給它分配string
。
在這里,您嘗試為可能不存在的 object 屬性設置新值。
所以是的,不能在賦值的左側使用可選的屬性訪問。
您可以在提案中閱讀更多相關信息
objectVariableName!.propertyName = 'some value to assign';
請注意感嘆號,即!
您也可以通過提前返回來解決此問題:
const output = document.getElementById('output');
if (!output) return;
output.innerHTML = url.toString()
像這樣對嵌套屬性使用它:
if (!item?.text) return;
item.text.text = action.payload.text;
在 ES12 中,你可以使用邏輯無效賦值來做到這一點
document.getElementById('output')?.innerHTML ??= url.toString()
所以只有當左邊的表達式不為空時才會發生賦值。
這就像你願意
if (document.getElementById('output')?.innerHTML) {
document.getElementById('output').innerHTML = url.toString()
}
這個非常簡短的表達式在 typescript 4.0.3 中非常適合我
let domEl: HTMLElement | null = document.querySelector("#app");
domEl && (domEl.style.color = "green");
只需 go 到tsconfig.json “compilerOptions”:{
刪除這個
"strict": true,
並添加這個
"strictPropertyInitialization": false,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.