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

 

๋ฐ˜์‘ํ˜•