Skip to content

πŸ’Ÿ [3μž₯] μΈλ±μŠ€λ“œ μ—‘μ„ΈμŠ€ νƒ€μž… 예제 였λ₯˜ 제보~!

drizzle96 edited this page Jun 6, 2024 · 1 revision
const metaData: MetadataProps = {
	author: "μ—°μš°",
	createdAt: 2024-06-06,
	chapter: 3,
	description: "μΈλ±μŠ€λ“œ μ—‘μ„ΈμŠ€ νƒ€μž… 예제 였λ₯˜ 제보~!"
	}
	
const { chapter, description } = metaData;

3.2.4 인덱슀트 μ—‘μ„ΈμŠ€ νƒ€μž…(p.101) μ˜ˆμ œμ— 였λ₯˜κ°€ μžˆλŠ” 것 κ°™μ•„ μ œλ³΄ν•©λ‹ˆλ‹€~! 그런데 제 λ‡Œν”Όμ…œμ΄λΌ μ œκ°€ ν‹€λ¦° 뢀뢄이 μžˆμ„ μˆ˜λ„ μžˆμŠ΅λ‹ˆλ‹€,,γ…Žγ…Ž

μ•„λž˜λŠ” μ±…μ˜ 예제인데 IDE에 κ·ΈλŒ€λ‘œ μž‘μ„±ν•˜λ©΄ μ—λŸ¬κ°€ μ—¬λŸΏ λ°œμƒν•©λ‹ˆλ‹€.

const PromotionList = [
  { type: 'product', name: 'chicken' },
  { type: 'product', name: 'pizza' },
  { type: 'card', name: 'cheer-up' },
]

// 1) 'T' only refers to a type, but is being used as a value here.
type ElementOf<T> = typeof T[number]

// 2) 'PromotionList' refers to a value, but is being used as a type here. Did you mean 'typeof PromotionList'?
type PromotionItemType = ElementOf<PromotionList>

μš°μ„  2λ²ˆμ€ μ—λŸ¬ λ©”μ‹œμ§€ κ·ΈλŒ€λ‘œ νƒ€μž…μ΄ λ“€μ–΄κ°ˆ μžλ¦¬μ— 값을 λ„£μ–΄μ„œ λ°œμƒν•˜λŠ” μ—λŸ¬λ‘œ typeof PromotionList둜 고치면 ν•΄κ²°λ©λ‹ˆλ‹€.

1λ²ˆμ€ μ—λŸ¬ λ©”μ‹œμ§€μ— λ”°λ₯΄λ©΄ 2번과 λ°˜λŒ€ μƒν™©μœΌλ‘œ 값이 λ“€μ–΄κ°ˆ μžλ¦¬μ— νƒ€μž…μ„ λ„£μ–΄μ„œ λ°œμƒν•˜λŠ” μ—λŸ¬μž…λ‹ˆλ‹€. typeof + κ°’ => νƒ€μž…μ΄ λ˜λŠ” 건데 κ°’ μžλ¦¬μ— μ œλ„€λ¦­ νƒ€μž… Tλ₯Ό λ„£μ–΄μ„œ μ—λŸ¬κ°€ λ°œμƒν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€. Tκ°€ νƒ€μž…μΈλ° ꡳ이 μ•žμ— typeofλ₯Ό 뢙일 ν•„μš”κ°€ μ—†μŠ΅λ‹ˆλ‹€.

const PromotionList = [
  { type: 'product', name: 'chicken' },
  { type: 'product', name: 'pizza' },
  { type: 'card', name: 'cheer-up' },
]

// 3) Type 'number' cannot be used to index type 'T'.
type ElementOf<T> = T[number]

type PromotionItemType = ElementOf<typeof PromotionList>

ν•˜μ§€λ§Œ μ—¬μ „νžˆ 3번 μ—λŸ¬κ°€ λ°œμƒν•©λ‹ˆλ‹€. μ΄λŠ” T의 ν˜•νƒœλ₯Ό λͺ¨λ₯΄λŠ”데 number둜 μΈλ±μŠ€λ“œ μ—‘μ„ΈμŠ€λ₯Ό μ‹œλ„ν–ˆκΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€. λ”°λΌμ„œ T에 λ°°μ—΄ ν˜•νƒœλ§Œ μ˜€λ„λ‘ μ œν•œν•΄μ•Ό ν•©λ‹ˆλ‹€.

const PromotionList = [
  { type: 'product', name: 'chicken' },
  { type: 'product', name: 'pizza' },
  { type: 'card', name: 'cheer-up' },
]

type ElementOf<T extends any[]> = T[number]

type PromotionItemType = ElementOf<typeof PromotionList>

이제 (any μ‚¬μš©μ„ μ œμ™Έν•˜λ©΄) μ—λŸ¬λŠ” ν•΄κ²°λμŠ΅λ‹ˆλ‹€~!!

λ³„κ°œλ‘œ ElementOf 역할을 ν•˜λŠ” μœ ν‹Έλ¦¬ν‹° νƒ€μž…μ€ 5μž₯의 inferλ₯Ό μ‚¬μš©ν•΄λ„ λ§Œλ“€ 수 μžˆμŠ΅λ‹ˆλ‹€. 이러면 anyλ₯Ό μ•ˆ μ“Έ 수 μžˆκ² λ„€μš”!

type ElementOf<T> = T extends (infer E)[] ? E : never
Clone this wiki locally