๋ฐ์ํ
๋ฌธ์
๋ฐฐ์ด(ํํ)์ ๋ฐ์, ๊ฐ ์์์ ๊ฐ์ key/value๋ก ๊ฐ๋ ์ค๋ธ์ ํธ ํ์ ์ ๋ฐํํ๋ ํ์ ์ ๊ตฌํํ์ธ์.
์์
const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
type result = TupleToObject<typeof tuple> // expected { tesla: 'tesla', 'model 3': 'model 3', 'model X': 'model X', 'model Y': 'model Y'}
ํ์ด
๊ฐ์ฒด์ ํค๋, ๊ฐ๋ T๋ฐฐ์ด์ ์์๊ธฐ ๋๋ฌธ์ ํค๊ฐ kv๊ฐ T[number]์ ์ํด์๊ณ ์ด ๊ฒ์ด ํค์ธ ๋์์ ๊ฐ์ด๋ผ๊ณ ๋ช ์ํด์ฃผ๋ฉด ํด๊ฒฐ๋๋ค.
์ด๋ T๋ string ๋๋ number ๊ฐ ํฌํจ๋ ๋ฐฐ์ด์ด๋ผ๋ ์ ๋ ๋ช ์ํด์ค๋ค.
type TupleToObject<T extends readonly (string|number)[]> = {
[kv in T[number]] : kv;
}
์ถ์ฒ
๋ฐ์ํ
'๐ Type Challenges > type-challenges' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TS] type-challenges: 18. Length of Tuple (0) | 2023.07.05 |
---|---|
[TS] type-challenges: 14. First of Array (0) | 2023.07.04 |
[TS] type-challenges : 7. Readonly (0) | 2023.06.28 |
[TS] type-challenges : 4. Pick (0) | 2023.06.28 |
[TS] type-challenges : 13. Hello World (0) | 2023.06.28 |