fruits
라는 문자열 배열로 시작합니다.
const fruits = ["apple", "banana", "orange"]
이것을 보면 배열의 값이 필요하다는 것을 알 수 있으므로 이에 대해 생각해 보세요.
여러분의 과제는 배열에 있는 모든 과일로 union을 만드는 것뿐만 아니라 AppleOrBanana
의 union을 구하는 것입니다.
type AppleOrBanana = unknown
type Fruit = unknown
type tests = [
Expect<Equal<AppleOrBanana, "apple" | "banana">>,
Expect<Equal<Fruit, "apple" | "banana" | "orange">>
]
import { Equal, Expect } from '../helpers/type-utils';
const fruits = ['apple', 'banana', 'orange'] as const;
type AppleOrBanana = typeof fruits[0 | 1];
type Fruit = typeof fruits[number];
type tests = [
Expect<Equal<AppleOrBanana, 'apple' | 'banana'>>,
Expect<Equal<Fruit, 'apple' | 'banana' | 'orange'>>
];
뭔가 좀 아쉽다?
가장 먼저 해야 할 일은 fruit
배열에 as const
를 사용하여 각 요소가 리터럴 타입이 되도록 하는 것입니다.
const fruits = ["apple", "banana", "orange"] as const
그런 다음 typeof fruits
에 0 | 1
의 indexed access 타입을 사용하여 배열에 액세스 합니다.
type AppleOrBanana = typeof fruits[0 | 1]