๐ฅ TypeScript Optional Chaining์์ ํํ ๋ฐ์ํ๋ ์ค๋ฅ
“Parsing error: Identifier expected.” ํด๊ฒฐํ๊ธฐ
TypeScript / ESLint๋ฅผ ์ฌ์ฉํ๋ค ๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ์ ์๋ฌ๋ฅผ ๊ฒฝํํ๋ ๊ฒฝ์ฐ๊ฐ ๋ง๋ค.
์ฒ์ ๋ณด๋ฉด ๋ฌด์จ ๋ง์ธ์ง ๊ฐ์ด ์ ์ค๋ ์๋ฌ์ง๋ง, ๋๋ถ๋ถ์ ๋ฌธ๋ฒ์ ์ผ๋ก ์๋ชป๋ optional chaining ์ฌ์ฉ ๋๋ฌธ์ ๋ฐ์ํ๋ค.
์ด๋ฒ ๊ธ์์๋ ์ค์ ๋ก ํํ๊ฒ ๋ฐ์ํ๋ ์ํฉ์ ์ฝ๊ฒ ์ ๋ฆฌํด๋ณด๊ฒ ๋ค.
โ ์๋ชป๋ ์ฝ๋ ์์
์๋ฅผ ๋ค์ด API ์๋ต์ ๋ฐ์ ๋ค ๋ฐฐ์ด์ ์ฒซ ๋ฒ์งธ ๊ฐ์ ์์ ํ๊ฒ ์ ๊ทผํ๋ ค๊ณ ์ด๋ ๊ฒ ์ฌ์ฉํ ๋๊ฐ ์๋ค:
๊ฒ๋ณด๊ธฐ์๋ ๋ง๋ ๊ฒ ๊ฐ์ง๋ง, items?[0] ๋ TypeScript ๋ฌธ๋ฒ์ด ์๋๋ค.
๊ทธ๋์ ESLint๋ parsing error๋ฅผ ๋์ง๋ค.
๐ ์ ์ค๋ฅ๊ฐ ๋ฐ์ํ ๊น?
JavaScript / TypeScript์ optional chaining ๋ฌธ๋ฒ์ ์ ํด์ง ํํ๊ฐ ์๋ค.
- ๊ฐ์ฒด ์ ๊ทผ → obj?.value
- ํจ์ ํธ์ถ → fn?.()
- ๋ฐฐ์ด ์ ๊ทผ → arr?.[0]
์ฆ, ๋ฐฐ์ด ์ธ๋ฑ์ค๋ฅผ optional chaining์ผ๋ก ์ ๊ทผํ ๋๋ ๋ฐ๋์ .?[0]์ด ์๋๋ผ ?.[0] ํํ์ฌ์ผ ํ๋ค.
๊ทธ๋์ obj?[0] ์ ๊ฐ์ ์ฝ๋๋ ๋ฌธ๋ฒ์ ์ผ๋ก ์์ ํ ์๋ชป๋ ์ฝ๋๋ค.
ํ์๋ ? ๋ค์์ ์ฌ๋ฐ๋ฅธ ์๋ณ์(identifier)๊ฐ ์ค์ง ์์ผ๋ ๋ฌธ๋ฒ ์ค๋ฅ๋ฅผ ๋ฐ์์ํค๋ ๊ฒ์ด๋ค.
โ ์ฌ๋ฐ๋ฅธ ์ฝ๋
์ด๋ ๊ฒ ์์ฑํด์ผ TypeScript๊ฐ:
- items๊ฐ undefined๋ฉด → undefined ๋ฐํ
- items๊ฐ ๋ฐฐ์ด์ด๋ฉด → ์ฒซ ๋ฒ์งธ ์์ ๋ฐํ
์ผ๋ก ๋์ํ๋ค.
๐งฉ ๋ ์์ ํ๊ฒ null ๊ฐ๋ ์ฒ๋ฆฌํ๊ณ ์ถ๋ค๋ฉด?
API ์๋ต์ด null์ ํฌํจํ ์ ์๋ค๋ฉด ??๋ฅผ ํจ๊ป ์ฌ์ฉํด ์์ ์ฑ์ ๊ฐํํ ์ ์๋ค.
์ด ๊ฒฝ์ฐ:
- items๊ฐ undefined → ''
- items๊ฐ [] → ''
- items[0]์ด null → ''
- items[0]์ด string → ๊ทธ๋๋ก ๋ฐํ
๐ ์์ฝ
| โ arr?[0] | TypeScript ๋ฌธ๋ฒ ์ค๋ฅ → Parsing error ๋ฐ์ |
| โ arr?.[0] | ์ฌ๋ฐ๋ฅธ optional chaining ๋ฐฐ์ด ์ ๊ทผ |
| โ arr?.[0] ?? '' | undefined/null ๋๋น๊น์ง ์์ ํ๊ฒ ์ฒ๋ฆฌ |
๐ฏ ๊ฒฐ๋ก
“Parsing error: Identifier expected.” ์๋ฌ๋ ๋๋ถ๋ถ optional chaining ๋ฌธ๋ฒ์ ์๋ชป ์ฌ์ฉํ์ ๋ ๋ฐ์ํ๋ค.
ํนํ ๋ฐฐ์ด ์ ๊ทผ ์ ๋ฌธ๋ฒ์ด ๊น๋ค๋ก์ด๋ฐ, ์ ๋ต์ ๋ค์ ํ ์ค์ด๋ค.
arr?.[0]
์ด๊ฑธ ๊ธฐ์ตํ๋ฉด ์์ผ๋ก ๋์ผํ ๋ฌธ์ ๋ก ๊ณ ์ํ ์ผ์ด ์๋ค.
'Project > ์๋ฌํด๊ฒฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [ERROR] (1) | 2025.07.11 |
|---|---|
| [ERROR]SQL Server์์ "Collation conflict" ์ค๋ฅ ํด๊ฒฐํ๊ธฐ (0) | 2025.06.18 |
| Java UnsupportedOperationException ์ค๋ฅ ํด๊ฒฐ (1) | 2025.04.24 |
| Type definition error: [simple type,~~~] (0) | 2025.03.21 |
| [ERROR] Module already exists (1) | 2025.02.16 |