타입 애너테이션

zimablue·2023년 8월 13일

typescript

목록 보기
1/18

Type Annotation


데이터 타입을 지정하기 위해 사용하며 변수 이름 뒤에 콜론과 타입을 입력하여 사용합니다.



예시

string type

// 변수선언문/ 변수명 / 콜론/ 타입/ 대입연산자/ 값
let whatWeStudy: string = 'TypeScript'


whatWeStudy = 'TypeAnnotation'


// 타입에 없는 매서드 사용시 에러
// Property 'upper' does not exist on type 'string'.
whatWeStudy.upper();


// 다른 타입 입력시 에러
// Type 'number' is not assignable to type 'string'
whatWeStudy = 9

other types

// number
let numCatLives: number = 9;

// boolean
let gameOver: boolean = false;

// any
// 모든 타입으로 바꿀 수 있음
let thing: any = "hello";
thing = 1;
thing = false;
thing();
thing.toUpperCase();

// unknown
// 변수의 타입을 미리 알지 못 할 때 사용
// 사용전 타입 확인을 강제
let a: unknown
if(typeof a === "number"){
	let b = a + 1
}
if(typeof a === "string"){
	let b = a.toUpperCase();
}

// void
// 아무것도 반환하지 않는 함수
function hell(): void {
	console.log("x")
}

// never
// 예외가 발생해도 절대 반환하지 않는 함수
function hell(): never {
	throw new Error("x")
}





Type Inference


타입 애너테이션을 지정하지 않아도 타입 스크립트는 타입 추론을 통해 변수 선언에 어떤 타입 값이 할당되었는지 파악합니다.

let tvShow = "Olive Kitteridge";

// Type 'boolean' is not assignable to type 'string'
tvShow = false;



암묵적 any

변수 선언과 초기화의 시기가 다를 때 Type Inference를 사용하면 변수를 암시적으로 any 타입으로 추론합니다.

암시적으로 any 타입으로 할당이 되면 컴파일하고 실행하게 되었을 때 오류가 발생할 수 있습니다.
그래서 이러한 경우, Type Annotation이 필요합니다.

수정 전

const movies = ["Arrival", "The Thing", "Aliens", "Amadeus"];
// Variable 'foundMovie' implicitly has an 'any' type, but a better type may be inferred from usage.
let foundMovie;

for (let movie of movies) {
  if (movie === "Amadeus") {
    // foundMovie: any
    foundMovie = "Amadeus";
  }
}

수정 후

const movies = ["Arrival", "The Thing", "Aliens", "Amadeus"];
let foundMovie: string;

for (let movie of movies) {
  if (movie === "Amadeus") {
    foundMovie = "Amadeus";
  }
}

2개의 댓글

comment-user-thumbnail
2023년 8월 13일

정리가 잘 된 글이네요. 도움이 됐습니다.

1개의 답글