Closed gwangminjun closed 3 weeks ago
점진적 구현: 향후 확장을 고려하여 현재는 필수가 아니지만 나중에 사용될 수 있는 프로퍼티를 정의할 때 사용합니다.
interface User {
id: number;
name: string;
email?: string; // 옵셔널 프로퍼티
}
function createUser(user: User): User {
return user;
}
// 이메일은 옵셔널 프로퍼티이므로 선택적으로 입력받음.
const user1 = createUser({ id: 1, name: "Jay" });
const user2 = createUser({ id: 2, name: "Soi", email: "soi@citty.com" });
타입 가드 사용: 해당 프로퍼티가 존재하는지 확인.
function printUserEmail(user: User) {
if (user.email) { // 안전한 접근
console.log(user.email);
} else {
console.log("이메일이 없습니다.");
}
}
Null 타입 검사 : Nullish 연산자로 대응
function getUserAge(user: User) {
return user.age ?? "해당 정보가 없습니다.";
}
옵셔널 체이닝 사용 : 중첩객체에 있는 옵셔널 프로퍼티에 안전하게 접근
interface Address {
street?: string;
city?: string;
}
type UserWithAddress {
address?: Address; // Address 타입 옵셔널 프로퍼티로 지정
}
function getUserCity(user: UserWithAddress) {
return UserWithAddress.address?.city ?? "해당 정보가 없습니다.";
}
interface User {
name: string; // 필수
email: string; // 필수
address?: string; // 선택
}
let user = undefined
user?.name = '홍길동'
console.log(user.name); // 에러 발생 > 위 단계에서 아무 일도 일어나지 않았기 때문에 name이 존재하지 않는다.
// user가 null 혹은 undefined가 아니라면 할당 가능
2. undefined일 수 있으므로 undefined 체크
객체의 속성이 선택적일때 사용한다
interface User {
name: string;
habbit?: string; // age는 선택적 프로퍼티입니다.
}
const user1: User = {
name: "minjun",
habbit: "study"
};
const user2: User = {
name: "Bob"
};
옵셔널 프로퍼티는 정의 되지 않을수있기 때문에 기본값을 정의하지 않는경우 undefined 값 처리시 문제가 발생한다
객체 구조 할당 처리 예시
interface UserSettings {
theme?: string;
notifications?: boolean;
}
function applySettings(settings: UserSettings) {
const { theme, notifications } = settings;
console.log(`Theme: ${theme}`);
console.log(`Notifications: ${notifications}`);
}
//객체 구조 할당
const userSettings: UserSettings = { theme: 'dark' };
// 출력: Theme: dark
// 출력: Notifications: undefined
//(기본값이 없으므로, notifications가 undefined일 때 처리되지 않음)
applySettings(userSettings);
옵셔널 프로퍼티는 특정 객체의 프로퍼티가 반드시 필요하지 않은 경우에 사용
객체 생성시 일부 프로퍼티가 선택 사항일 때
class Person {
name: string;
age: number;
email?: string;
address?: string;
constructor(name: string, age: number, email?: string, address?: string) { this.name = name; this.age = age; this.email = email; this.address = address; } }
// 모든 프로퍼티를 포함하여 객체를 생성 const person1 = new Person('person1', 30, 'emain@example.com', '123 Main St');
// 선택적인 프로퍼티 없이 객체를 생성 const person2 = new Person('persen2', 25);
2. 초기 상태가 불완전 할 때
- 비동기 작업에서 데이터가 로드되기전에 객체를 미리 생성해야할 때
```ts
class UserProfile {
name?: string;
age?: number;
email?: string;
constructor() {
// 초기에는 비어 있는 상태로 객체를 생성
}
// 데이터가 로드된 후에 프로퍼티를 설정
loadData(data: { name: string, age: number, email: string }) {
this.name = data.name;
this.age = data.age;
this.email = data.email;
}
}
// 객체를 먼저 생성
const user = new UserProfile();
// 비동기 작업에서 데이터를 가져오는 예시
setTimeout(() => {
const data = { name: 'user1', age: 30, email: 'user1@example.com' };
user.loadData(data);
console.log(user);
}, 1000);
주의해야할 사항 1) 타입 추론 주의
2) 초기화에 신중
3) 디폴트 갑 고려
수고하셨습니다~
📝 94p
❓ 타입스크립트에서 옵셔널 프로퍼티와 필수 프로퍼티를 구분할 때, 옵셔널 프로퍼티를 사용해야 하는 상황은 어떤 경우인가요?
또한 옵셔널 프로퍼티를 사용할때 주의할점은 무엇인가요?