Programming/TypeScript

[TypeScript] The left-hand side of an assignment expression may not be an optional property access 였λ₯˜ 원인 및 ν•΄κ²° 방법

yuri lee 2023. 3. 3. 20:48
λ°˜μ‘ν˜•

Intro

μ•ˆλ…•ν•˜μ„Έμš”. TypeScript νƒ€μž…μŠ€ν¬λ¦½νŠΈμ—μ„œ refλ₯Ό μ‚¬μš©ν•˜μ—¬ scrollTop μœ„μΉ˜λ₯Ό λ³€κ²½ν•˜λ˜ 도쀑 μ•„λž˜μ™€ 같은 μ—λŸ¬κ°€ λ°œμƒν•˜μ˜€μŠ΅λ‹ˆλ‹€

 

someRef?.current?.scrollTop = 0;

 

TS2779: The left-hand side of an assignment expression may not be an optional property access

 

 

Why?

μŠ€νŽ™ μƒμ—μ„œ μ˜΅μ…”λ„ 체이닝과 할당을 같이 μ‚¬μš©ν•  수 μ—†λ‹€κ³  ν•©λ‹ˆλ‹€. 

The following is not supported, although it has some use cases; see Issue #18 for discussion:
optional property assignment: a?.b = c

 

How to solve the problem

μ½”λ“œλ₯Ό λ‹€μŒκ³Ό 같이 μˆ˜μ •ν•œ κ²°κ³Ό, 더 이상 ν•΄λ‹Ή μ—λŸ¬κ°€ λ°œμƒν•˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. 

 if (someRef?.current?.scrollTop) {
    someRef.current.scrollTop = 0;
}

 

이 외에도 μ•„λž˜μ™€ 같이 μˆ˜μ •ν•˜μ‹€ μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€. 

 if (someRef.current.scrollTop != null) {
    someRef.current.scrollTop = 0;
}

https://github.com/tc39/proposal-optional-chaining#not-supported

 

λ°˜μ‘ν˜•