기본 타입

💡
기본적인 데이터 타입 정리하기

공식 문서에서 자바스크립트와 동일하지 않거나 새로 나온 부분만 정리

불리언

숫자

let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

문자열

배열

튜플

  1. 요소의 타입과 개수가 고정된 배열을 표현 가능
    • 요소들의 타입이 모두 같을 필요는 없음
  1. 정해진 인덱스의 요소는 미리 정의된 타입을 반환 함
    • 예를 들어 넘버로 정의한 인덱스에 string 의 split 같은 함수를 호출하려하면 에러가 발생한다는 뜻
  1. 배열과 다르게 정해진 인덱스가 아닌 곳에 접근하면 에러 발생
// 1 튜플 타입으로 선언
let x: [string, number];
// 초기화
x = ["hello", 10]; // 성공
// 잘못된 초기화
x = [10, "hello"]; // 오류

// 2
console.log(x[0].substring(1)); // 성공
console.log(x[1].substring(1)); // 오류, 'number'에는 'substring' 이 없습니다.

// 3
x[3] = "world"; // 오류, '[string, number]' 타입에는 프로퍼티 '3'이 없습니다.
console.log(x[5].toString()); // '[string, number]' 타입에는 프로퍼티 '5'가 없습니다.

열거형 (Enum)

// 사용 방법
enum Color {Red, Green, Blue}
let c: Color = Color.Green;

UnKnown

let notSure: unknown = 4;
notSure = "maybe a string instead";

// OK, definitely a boolean
notSure = false;

Any

let looselyTyped: any = 4;
// OK, 런타임에는 ifItExists 라는 속성이 있을수도 있음!
looselyTyped.ifItExists();
// OK, toFixed 가 존재하므로 컴파일 성공 (하지만 실제로 컴파일러는 체크하지 않는다)
looselyTyped.toFixed();

let strictlyTyped: unknown = 4;
strictlyTyped.toFixed();
// Error, Object is of type 'unknown'.
let looselyTyped: any = {};
let d = looselyTyped.a.b.c.d;
//  ^ = let d: any

any 와 unknown 의 차이

Void

Null and Undefined

// 이 밖에 이 변수들에 할당할 수 있는 값이 없음
let u: undefined = undefined;
let n: null = null;

Never

// never를 반환하는 함수는 함수의 마지막에 도달할 수 없다.
function error(message: string): never {
    throw new Error(message);
}

// 반환 타입이 never로 추론된다.
function fail() {
    return error("Something failed");
}

// never를 반환하는 함수는 함수의 마지막에 도달할 수 없다.
function infiniteLoop(): never {
    while (true) {
    }
}

Object

Type assertions

About Number, String, Boolean, Symbol and Object