728x90
TS Utility Types
📌 partial
필수 사항을 선택사항으로 변경
interface Toppings {
tomatoes: boolean;
onion: boolean;
lettuce: boolean;
ketchup: boolean;
}
const myToppings: Toppings = {
tomatoes: true,
onion: true,
lettuce: true,
ketchup: true,
};
const partialToppingsIWant: Partial<Toppings> = {
tomatoes: true,
onion: undefined,
};
console.log(
"~ file: index.ts:19 ~ partialToppingsIWant",
partialToppingsIWant
)
myToppings는 tomatoes, onion, lettuce, ketchup 중 하나라도 없으면, 에러 발생
하지만 partialToppingsIWant의 경우 부분적으로 사용해도 에러가 발생하지 않음
📌 Required
interface BubbleTeaOrder {
tea: boolean;
straw?: boolean;
}
const myBubbleTeaOrder: Required<BubbleTeaOrder> = {
tea: true,
straw: true,
};
straw는 필수 입력사항이 아니지만, required 지정해주면 필수 입력사항이 된다.
📌 readonly
interface BankAccount {
accountNumber: string;
balance: bigint;
}
const myAccount: Readonly<BankAccount> = {
accountNumber: "1234",
balance: BigInt(10000000),
};
myAccount.balance = BigInt(0); // 재할당 불가능
console.log(myAccount);
📌 record<keys, values>
type Type = string[];
type TypeII = Array<string>;
type ObjectTypeRecord = Record<string, string>;
type ObjectTypeObject = { [x: string]: string };
type Country = "Korea" | "USA" | "Canada" | "UK";
type CountryCode = 82 | 1 | 44;
type CountryToCountyCode = Record<Country, CountryCode>;
type CountryToCountyCodeObject = { [countryName in Country]: CountryCode };
const countries: CountryToCountyCodeObject = {
Korea: 82,
USA: 1,
Canada: 1,
UK: 44,
};
📌 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",
// password: "1234", // 에러 발생
// email: "hello@world.hello", // 에러 발생
}
왜냐하면 LessUserInfo 타입은 다음과 같아 지기 때문이다.
type LessUserInfo = {
userName: string;
favoriteColor: string;
}
📌 Exclude<UnionType, ExcludedMembers>
omit과 유사.
특정 프로퍼티 제외
type MyType = "dog" | "cat" | "alpaca";
type LessMyType = Exclude<MyType, "alpaca">; // type LessMyType = "dog" | "cat"
함수 타입
type onChange = (isDone: boolean) => boolean;
type GruopOfTypes = string | undefined | onChange;
type FunctionType = Exclude<GruopOfTypes, string | undefined>; // type FunctionType = (isDone: boolean) => boolean
const onChangeHandler: FunctionType = (isDone) => isDone;
console.log(onChangeHandler(true)); // true
📌 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,
};
console.log(studentName);
📌 Extract<Type, Union>
꼭 필요한 유니언만 뽑아오는 것.
type MyPet = "dog" | "cat" | "alpaca";
type ExtractedMyPet = Extract<MyPet, "alpaca" | "cat">;
const onlyAlpacaOrCatAllowed: ExtractedMyPet = "alpaca";
dog를 onlyAlpacaOrCatAllowed변수에 할당하면 에러 발생.
📌 NonNullable<Type>
type QueryParam = string | string[] | undefined | null;
type NonNullableQueryParam = NonNullable<QueryParam>;
const QueryParam: NonNullableQueryParam = ["orders"];
const forbiddenQueryParam: NonNullableQueryParam = undefined; // 허용안됨
const forbiddenQueryParamII: NonNullableQueryParam = null; // 허용안됨
'JavaScript' 카테고리의 다른 글
TS 입문 주차 (0) | 2023.01.30 |
---|---|
TS, 기본적인 CRUD (0) | 2023.01.30 |
Type Script 제너릭타입(Generic types) (0) | 2023.01.26 |
Type Script 열거형(Enums) (0) | 2023.01.26 |
TS, 내가 만든 포켓몬 크롤링 프로그램 (0) | 2023.01.19 |