[TypeScript] 타입스크립트에서의 !(느낌표)

김진영·2023년 5월 17일
0

TypeScript

목록 보기
2/3
post-thumbnail

📋 타입스크립트에서의 느낌표

JS를 포함한 대부분의 언어에서 느낌표는 대부분 False를 의미하는 연산자이다.

하지만 타입스크립트에서는 느낌표를 변수 뒤에 붙이면 False가 아닌 다른 방식으로 사용할 수 있다.
어떤 방식으로 사용할 수 있는지 함께 알아보자.


📌 1. Null이 아닌 단언 연산자(Non-null assertion operator)

Null이 아닌 단언 연산자(Non-null assertion operator)는 피연산자가 null이 아니라고 컴파일러에게 전달하여 일시적으로 null 제약 조건을 완화한다.

이 코드를 살펴보자.

interface HumanType {
  name: string;
  born: string;
  died: string | null;
}

const michaelJackson: HumanType = {
  name: "Michael Jackson",
  born: "1958년 8월 29일",
  died: "2009년 6월 25일"
};

const kendrickLamar: HumanType = {
  name: "Kendrick Lamar",
  born: "1987년 6월 17일",
  died: null
};

console.log(michaelJackson.died.toString());
//Error! 'michaelJackson.died' is possibly 'null'.

이 코드를 보면 HumanType의 died는 string 또는 null일 수 있기 때문에 null일 수 있다는 에러가 나온다.

console.log(michaelJackson.died!.toString());

하지만 이처럼 느낌표를 추가해주면 오류가 해결된다.


📌 2. 확정 할당 단언(Definite Assignment Assertions)

확정 할당 단언(Definite Assignment Assertions)은 TypeScript 분석이 감지할 수 없더라도 변수가 실제로 할당되었음을 TypeScript에 알리기 위해 인스턴스 속성 및 변수 선언 후에 느낌표 (!)를 배치할 수 있는 기능입니다.
-typescriptlang.org

let x: number;
function initialize() {
  x = 10;
}
initialize();
console.log(x + x);
// Error! Variable 'x' is used before being assigned.

위 코드를 작동시키면 변수 x가 할당되기 전에 사용됐다는 오류 메세지가 나온다.

여기에 확정 할당 단언을 사용하면 x에 값이 무조건 할당되어있다고 컴파일러에게 전달하여 값이 없어도 x를 사용할 수 있게 된다.

let x!: number;
function initialize() {
  x = 10;
}
initialize();
console.log(x + x);

또한 이것은 밑의 예제처럼 변환도 가능하다.

let x: number;
function initialize() {
  x = 10;
}
initialize();
console.log(x! + x!);

참고

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions
https://inpa.tistory.com/entry/TS-%F0%9F%93%98-%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EB%8A%90%EB%82%8C%ED%91%9C-Non-null-%EB%8B%A8%EC%96%B8-%EC%97%B0%EC%82%B0%EC%9E%90

1개의 댓글

comment-user-thumbnail
2023년 6월 6일

👏

답글 달기