interface User {
id: number;
name: string;
age: number;
gender: 'm' | 'f';
}
type UserKey = keyof User; // 'id' | 'name' | 'age' | 'gender'
const uk: UserKey = 'id';
interface User {
id: number;
name: string;
age: number;
gender: 'm' | 'f';
}
let admin: Partial<User> = {
id: 1,
name: 'Bob',
};
/*
이것과 같음
interface User {
id?: number;
name?: string;
age?: number;
gender?: 'm' | 'f';
}
*/
interface User {
id: number;
name: string;
age?: number;
}
let admin: Required<User> = {
id: 1,
name: 'Bob',
age: 30,
};
interface User {
id: number;
name: string;
age?: number;
}
let admin: Readonly<User> = {
id: 1,
name: 'Bob',
age: 30,
};
admin.id = 4; // 에러 발생
interface Score {
'1': 'A' | 'B' | 'C' | 'D';
'2': 'A' | 'B' | 'C' | 'D';
'3': 'A' | 'B' | 'C' | 'D';
'4': 'A' | 'B' | 'C' | 'D';
}
const score: Score = {
1: 'A',
2: 'C',
3: 'B',
4: 'D',
};
type Grade = '1' | '2' | '3' | '4';
type Score = 'A' | 'B' | 'C' | 'D' | 'F';
const score: Record<Grade, Score> = {
1: 'A',
2: 'C',
3: 'B',
4: 'D',
};
interface User {
id: number;
name: string;
age: number;
}
function isValid(user: User) {
const result: Record<keyof User, boolean> = {
id: user.id > 0,
name: user.name !== '',
age: user.age > 0,
};
return result;
}
interface User {
id: number;
name: string;
age: number;
gender: 'M' | 'W';
}
const admin: Pick<User, 'id' | 'name'> = {
id: 0,
name: 'Bob',
};
interface User {
id: number;
name: string;
age: number;
gender: 'M' | 'W';
}
const admin: Omit<User, 'age' | 'gender'> = {
id: 0,
name: 'Bob',
};
type T1 = string | number | Boolean;
type T2 = Exclude<T1, number | string>; // Boolean
type T1 = string | null | undefined | void;
type T2 = NonNullable<T1>; // string | void
참고 : 코딩앙마