객체의 속성에 접근할 때 해당 속성이 존재하지 않은 경우 에러를 발생시키지 않고 undefined를 반환하도록 하는 문법
?.let user = {
name: "John",
address: {
street: "123 Main St",
city: "New York"
}
};
// 존재하지 않는 속성에 접근할 때 에러 발생을 방지
console.log(user.address?.street); // 출력: "123 Main St"
console.log(user.address?.zipcode); // 출력: undefined
console.log(user.contact?.phone); // 출력: undefined
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob" }
];
// 존재하지 않는 배열 요소에 접근할 때 에러 발생을 방지
console.log(users[0]?.age); // 출력: 25
console.log(users[1]?.age); // 출력: undefined
console.log(users[2]?.age); // 출력: undefined
let user = {
greet: function() {
return "Hello!";
}
};
// 존재하지 않는 함수 호출을 방지
console.log(user.greet?.()); // 출력: "Hello!"
console.log(user.sayGoodbye?.()); // 출력: undefined
let user = {
profile: {
contacts: {
email: "user@example.com"
}
}
};
// 여러 단계의 속성 접근을 안전하게 처리
console.log(user.profile?.contacts?.email); // 출력: "user@example.com"
console.log(user.profile?.contacts?.phone); // 출력: undefined
console.log(user.profile?.friends?.[0]?.name); // 출력: undefined
옵셔널 체이닝을 활용해서 코드 작성 간 오타나 없는 속성 등으로 인해 오류를 내뿜던 것을 어느정도 해결 할 수 있어 정리해 봤다.
참 유용한 기능이다.
옵셔널 체이닝을 사용하면, 중첩된 객체 구조에서 특정 속성이나 메서드가 존재하지 않을 경우 에러를 피하고 undefined를 반환받을 수 있음
즉, ?. '앞’의 평가 대상이 undefined나 null이면 평가를 멈추고 undefined를 반환
=> 이를 통해 코드의 안정성과 가독성을 크게 향상
개인 공부 및 과제 기간이라 기존에 있던 개념들을 정리하고 넘어가고 싶어서 TypeScript 공부를 조금 늦추고 있다.
아직 다른 개념들도 낯선데 TypeScript는 얼마나 생소할까..