TS : 많이쓰는 Utility types
Partial<Type>
: 특정 타입에 속해있는 집합을 모두 optionalChaining로 만드는 타입으로 변환해준다.
interface Toppings {
tomatoes: boolean;
onion: boolean;
lettuce: boolean;
ketchup: boolean;
}
const toppingsIWant: Toppings = {
onion: true,
// 모든 토핑이 있어도 되고 없어도 됩니다
// undefined로 명시해줘도 됩니다
ketchup: undefined,
};
Required<Type>
: Partial의 반대로 특정 타입에 속해있는 optionalChaining을 포함한 모든 타입을 필수로 변환하는 타입
interface BubbleTeaOrder {
tea: boolean;
straw?: boolean;
}
const myBubbleTeaOrder: Required<BubbleTeaOrder> = {
tea: true,
straw: true,
};
Readonly<Type>
: 한 타입의 집합을 읽기권한만 가능하게 변환해주는 타입
interface BankAccount {
accountNumber: string;
balance: bigint;
}
const myAccount: Readonly<BankAccount> = {
accountNumber: "1234",
balance: BigInt(Number.MAX_SAFE_INTEGER),
};
// 컴파일되지 않습니다
myAccount.accountNumber = "123"; // ❌ Cannot assign to 'accountNumber' because it is a read-only property.
myAccount.balance = BigInt(Number.MIN_VALUE); // ❌ Cannot assign to 'balance' because it is a read-only property.
Record<Keys, Type>
: 객체 타입을 설립하는데 쓰이는 유틸리티 타입
type Country = "Korea" | "USA" | "Canada" | "UK"; // enum으로 구현해도 됩니다
type CountryCode = 82 | 1 | 44; // enum으로 구현해도 됩니다
type CountryToCountryCode = Record<Country, CountryCode>;
const countries = {
Korea: 82,
USA: 1,
Canada: 1,
UK: 44,
};
// Record<Key, Type>은 객체를 사용한 타입 선언 방법과 같습니다.
type AnotherCountryToCountryCode = { [countryName in Country]: CountryCode };
Omit<Type, Keys>
: 특정 타입에 구성되어있는 프로퍼티를 생략시킬 때 쓰는 타입
interface UserInfo {
userName: string;
favoriteColor: string;
email: string;
password: string;
}
type LessUserInfo = Omit<UserInfo, "password" | "email">;
const newUser: LessUserInfo = {
userName: "pony",
favoriteColor: "rainbow",
// 생략시킨 email이 속해있어서 컴파일되지 않습니다
email: "hello@world.hello", // ❌ Object literal may only specify known properties, and 'email' does not exist in type 'LessUserInfo'.
};
Exclude<UnionType, ExcludedMembers>
: 유니언 타입에 속해있는 속성들을 생략할 때 쓰는 타입
type MyType = "dog" | "cat" | "alpaca";
type ExcludedType = Exclude<MyType, "cat" | "alpaca">;
const onlyDogAllowed: ExcludedType = "dog"; // ✅
const noAlpaca: ExcludedType = "alpaca"; // ❌
----------------------------------------------------
type OnChange = (isDone: boolean) => void;
type GroupOfTypes = string | undefined | OnChange;
type FunctionType = Exclude<GroupOfTypes, string | undefined>;
const onChangeHandler: FunctionType = (isDone) => console.log(isDone); // ✅
const today: ExcludedFunctionType = "great day"; // ❌
Pick<Type, Keys>
: 한 타입의 특정 프로퍼티들만 뽑아 쓸 수 있도록 도와주는 타입
interface User {
firstName: string;
lastName: string;
}
interface Student {
user: User;
isGraduated: boolean;
school: string;
}
type StudentName = Pick<Student, "user" | "isGraduated">;
const studentName: StudentName = {
user: {
firstName: "winnie",
lastName: "pooh",
},
isGraduated: true,
};
Extract<Type, Union>
: Exclude의 반대로, 타입에서 필요한 유니언만 뽑아오는 타입
type MyType = "dog" | "cat" | "alpaca";
type ExtractedType = Extract<MyType, "alpaca" | "cat">;
const onlyAlpacaOrCatAllowed: ExtractedType = "cat"; // 또는 "alpaca"만 할당 가능
NonNullable<Type>
: 특정 타입에서 null 또는 undefined 를 생략해주는 타입
type QueryParam = string | string[] | undefined | null;
type NonNullableQueryParam = NonNullable<QueryParam>;
const queryParam: NonNullableQueryParam = "orders"; // 문자열은 허용되는 타입입니다
const forbiddenQueryParam: NonNullableQueryParam = undefined; // 허용되지 않습니다