Non-null Assertion Operator(!)는 TypeScript에서 "이 값은 절대 null이나 undefined가 아닐 거야!"라고 컴파일러에게 알려주는 연산자.
let username: string | null = null;
// 에러 발생: username이 null일 수 있음
console.log(username.length);
// 정상 작동: "이 값은 null이 아니야!"라고 컴파일러에게 알려줌
console.log(username!.length);
React 컴포넌트에서 자주 볼 수 있는 예시:
const UserProfile = () => {
const [user, setUser] = useState<User | null>(null);
const handleSubmit = () => {
// user가 null일 수 있어서 에러 발생
sendUserData(user.id);
// '!'를 사용하면 에러 없음
sendUserData(user!.id);
}
}
let data: string | null = null;
console.log(data!.length); // 런타임 에러 발생!
// 1. 조건문으로 체크
if (data !== null) {
console.log(data.length);
}
// 2. 옵셔널 체이닝 사용
console.log(data?.length);
// 3. 기본값 설정
console.log(data ?? "기본값");
const header = document.querySelector('header')!;
class User {
name!: string; // 생성자가 아닌 다른 곳에서 반드시 초기화됨
}
// 좋지 않음
const response = await api.getUser();
console.log(response!.data);
// 더 나음
const response = await api.getUser();
if (response) {
console.log(response.data);
}
// 좋지 않음
function processUserInput(input: string | undefined) {
const length = input!.length; // 위험!
}
// 더 나음
function processUserInput(input: string | undefined) {
if (!input) return;
const length = input.length;
}
코드의 안전성을 높이기 위해서는 명시적인 null 체크를 하는 것이 좋음.