스파르타코딩클럽 내일배움캠프 Typescript 강의를 들으며 공부한 것을 적은 것입니다.
interface Toppings {
tomatoes: boolean;
onion: boolean;
lettuce: boolean;
ketchup: boolean;
}
위와 같은 인터페이스가 선언되어 있을 때,
const myToppings: Toppings = {
}
// error
// tomatoes, onion, lettuce, ketchup 속성이 없다
일반적인 방식으로 type을 지정해 줄 경우, 에러 발생한다.
const partialToppingsWant: Partial<Toppings> = {
}
Partial은 선택적으로 반환 하기 때문에 에러가 발생하지 않는다.
속성이 undefined 가 될 수 있다고 얘기해준다.
interface BubbleTeaOrder {
tea: boolean;
straw?: boolean;
}
위와 같은 인터페이스가 선언되어 있을 때,
straw가 ?: 로 필수 사항이 아니지만,
const myBubbleTeaOrder: Required<BubbleTeaOrder> = {
tea: true,
straw: true,
}
위와 같이 straw 를 필수로 true나 false를 반환하도록 한다.
interface BankAccount {
accountNumber: string;
balance: bigint;
}
위와 같은 인터페이스가 선언되어 있을 때,
const myAccount: Readonly<BankAccount> = {
accountNumber: "1234",
balance: BigInt(Number.MAX_SAFE_INTEGER),
};
myAccount 객체를 다음과 같이 선언하면,
myAccount.accountNumber = "123"
// error
읽기 전용이므로 값을 할당 할 수 없다는 에러가 발생한다.
type ObjectTypeRecord = Record<string, string>;
type ObjectTypeObject = {
[x: string]: string
}
// 위의 두개가 동일
type Country = "Korea" | "USA" | "UK";
type CountryCode = 82 | 1 | 44;
type CountryToCountryCode = Record<Country, CountryCode>;
const countries: CountryToCountryCode = {
Korea: 82,
USA: 1,
UK: 44,
}
interface UserInfo {
userName: string;
favoriteColor: string;
email: string;
password: string;
}
위와 같은 인터페이스가 선언되어 있을 때,
type LessUserInfo = Omit<UserInfo, "email" | "password">;
LessUserInfo 라는 타입을 다음과 같이 정의하면,
위와 같은 형태로 구성되는 것을 알 수 있다.
type MyType = "dog" | "cat";
type ExcludedMyType = Exclude<MyType, "cat">;
const noCat: ExcludedMyType = "cat" // error
interface User {
firstName: string;
lastName: string;
}
interface Student {
user: User;
school: string;
grade: number;
}
위와 같은 인터페이스가 선언되어 있을 때,
type StudentName = Pick<Student, "user" | "school">;
다음과 같은 타입을 정의했다면,
const studentName: StudentName = {
user: {
firstName: "Asher",
lastName: "Park",
},
school: "YU",
};
Student의 인터페이스에서 user Property와 school Property를 뽑아와 사용할 수 있다.
type MyType = "dog" | "cat" | "monkey";
type ExtractedType = Extract<MyType, "dog" | "cat">
const onlyDogOrCatAllowed: ExtractedType = "cat" // 또는 dog만 할당가능
type QueryParam = string | string[] | undefined | null;
type NonNullableQueryParam = NonNullable<QueryParam>;
const forbiddenQueryParam: NonNullableQueryParam = undefined; // error