본문 바로가기
개발/TypeScript

TypeScript의 기본 타입

by 안뇽! 2021. 11. 9.
반응형

TypeScript의 기본타입

JS에서 많이 본 타입

Boolean

const x : boolean = true;
const y : boolean = false;

Number

  • 자바스크립트에서는 정수, 부동 소수점 등의 구분이 따로 없고 모든 수가 IEEE754 표준을 따르는 부동소수점이고, 타입스크립트의 number 타입도 마찬가지다.
const x : number = 1;
const y : number = 0.2+0.1;

String

  • ES6 템플릿 리터럴 역시 string 타입의 값이다.
const name : string = 'June';
const sentence : string = '감사합니다'

null / undefined

  • null / undefined 타입은 자기 자신 외에는 다른값을 갖지 않는다.
  • 이 두 값을 자기 자신의 타입, 그리고 아래에서 언급될 void 타입 이외의 타입에 할당하려 하면 타입에러 (TS2322: Type 'null' is not assignable to type 'number' 등) 가 발생한다.
const nullValue : null = null;
const undefinedValue : undefined = undefined;
const numberValue : number = null ; // TS2322: Type 'null' is not assignable to type 'number'

JS에서 볼 수 없던 타입

any

  • any 타입은 모든 타입과 호환가능하다.
  • 모든 타입을 any로 지정할 수 있고, any 타입의 변수에는 모든 값을 할당할 수 있다.
  • 모르면 일단 any로 지정하고 나중에 수정한다.
let bool : any = true;
bool = 3;
bool = 'whatever';
bool = {};
  • any 타입은 타입스크립트 타임 시스템의 비상탈출구이다. 하지만 any를 남용하면 타입 안정성에 구멍이 뜷린 코드가 되어 타입스크립트를 사용하는 이유가 사라진다.

void

  • voidnullundefined 만을 값으로 가진다.
  • 주로 아무런 값도 반환하지 않는 함수를 작성할 때 void 타입을 사용한다.
  • void 타입이 아니면서 아무 값도 반환하지 않으면 타입에러가 발생한다.
function nothing () : void {}

// void 반환 타입을 갖는 함수가 undefined나 null 이외의 값을 반환하면 타입에러가 발생한다.
function notReallyVoid(): void {
  return 1;
}
// error TS2322: Type '1' is not assignable to type 'void'.


// void 타입이 아닌 함수가 아무 값도 반환하지 않는 경우에 타입에러가 발생한다.
function actuallyVoid(): number { }
// error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.

never

  • 아무런 값도 가질 수 없는 타입이다.
  • 아래 함수는 항상 에러를 throw 하므로 어떤 값도 반환하지 않는다. 에러 함수에 사용할 수 있다.
function alwaysThrow(): never {
  throw new Error(`I'm a wicked function!`);
}

출처
https://ahnheejong.gitbook.io/ts-for-jsdev/03-basic-grammar/primitive-types

반응형