프론트엔드 개발

타입스크립트 기본 타입 본문

Front-End/Typescript

타입스크립트 기본 타입

태나미 2021. 7. 3. 23:41

타입스크립트는 자바스크립트와 거의 동일한 데이터 타입을 지원하며, 기본 타입은 다음과 같다.

 

  • Boolean
  • Number
  • String
  • Array
  • Tuple
  • Enum
  • Any
  • Void
  • Null and Undefined
  • Never
  • Object

불리언 ( Boolean )

const isExist: booolean = true;

숫자( Number )

const myAge: number = 29;

문자열 ( String )

const firstName: string = "Kim";
const lastName: string = "Taenam";

const fullName: string = `${firstName} ${lastName}`

배열 ( Array )

배열 타입은 두 가지 방법으로 쓸 수 있다.

첫 번째 방법은, 배열 요소들을 나타내는 타입 뒤에 []를 쓰는 것이다

const alphabetical: string[] = ["a","b","c", ... "z"];
const middleSchoolClass: number[] = [1, 2, 3];

두 번째 방법은 제네릭 배열 타입을 쓰는 것이다. Array<elemType>:

const alphabetical: Array<string> = ["a","b","c", ... "z"];
const middleSchoolClass: Array<number> = [1, 2, 3];

튜플 ( Tuple )

요소의 타입과 개수가 고정된 배열을 표현할 때 쓸 수 있다.

또한, 정해진 인덱스 외에 다른 인덱스에 있는 요소에 접근하면, 오류가 발생한다.

const myInfo: [string, number] = ["KimTaenam", 29];

myInfo[1] = "developer"; // '문자열'유형은 '숫자'유형에 할당 할 수 없습니다.
myInfo[3] = "world"; // 길이가 '2'인 튜플 유형 '[string, number]'에 인덱스 '3'에 요소가 없습니다.

열거 ( Enum )

지정된 타입이 들어오는 경우 다른 값이 들어오는 것을 막기 위해 Enum으로 집합을 만들고, 그 이외의 값은 받지 않는다.

enum Color {Red, Green, Blue}
const favoriteColor: Color = Color.Green;

Any

'모든 타입에 대해서 허용한다'는 의미를 갖고 있다.

let notSure: any = 404;
notSure = "404, Error";
notSure = false

Void

함수에서 반환 값이 없을 때 반환 타입을 표현하기 위해 쓰이는 것을 볼 수 있다.

변수에는 undefined와 null만 할당하고, 함수에는 반환 값을 설정할 수 없는 타입이다.

const unusable: void = undefined;

function notReturnValue(): void {
  console.log("when return nothing");
}

Null and Undefined

const und: undefined = undefined;
const nul: null = null;

Never

함수의 마지막까지 도달하지 않는다는 의미를 지닌 타입, 절대로 발생하지 않는 값으로 에러 핸들링 함수에서 사용한다.

// 이 함수는 절대 함수의 끝까지 실행되지 않는다는 의미
function neverEnd(): never {
  while (true) {
    ...
  }
  // 여기는 도달하지 않아요
}

function errorThrow(): never {
  //에러 발생한 경우 중지하지 않고 throw 함수 실행
  throw new Error("error");
}

객체 ( object )

object는 primitive 타입이 아닌 object로 반환하는 모든 타입을 나타낸다.

const obj: object = {};
const arr: object = [];
const func: object = function() {};
const date: object = new Date();

const myInfo: { name: string, age: number } = {
  name: 'KimTaenam',
  age: 29
};

 

출처: https://typescript-kr.github.io/pages/basic-types.html

https://kyounghwan01.github.io/blog/TS/Fundamentals/basic/

https://joshua1988.github.io/ts/guide/basic-types.html#%ED%83%80%EC%9E%85%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EA%B8%B0%EB%B3%B8-%ED%83%80%EC%9E%85

 

Comments