TypeScript의 기본 타입은 JavaScript의 원시 타입에 정적 타입 표기 를 더한 것입니다.

원시 타입(Primitive Types)

string

TYPESCRIPT
// 문자열 타입
const name: string = '심정훈';
const greeting: string = `안녕하세요, ${name}님!`; // 템플릿 리터럴도 string

// ❌ 숫자를 넣으면 컴파일 에러
// const wrong: string = 42;

number

TYPESCRIPT
// 숫자 타입 — 정수와 소수를 구분하지 않음
const age: number = 25;
const pi: number = 3.14;
const hex: number = 0xff;    // 16진수도 number
const binary: number = 0b1010; // 2진수도 number

// NaN과 Infinity도 number 타입
const notANumber: number = NaN;
const infinity: number = Infinity;

면접에서 "TypeScript에 int, float 구분이 있나요?"라고 물어보면, 없다 고 답하면 됩니다. JavaScript와 동일하게 모든 숫자가 number 타입입니다.

boolean

TYPESCRIPT
// 불리언 타입
const isActive: boolean = true;
const hasPermission: boolean = false;

// ❌ truthy/falsy 값은 boolean이 아님
// const wrong: boolean = 1;     // Error
// const wrong2: boolean = 'yes'; // Error

bigint

TYPESCRIPT
// 큰 정수를 다룰 때 사용
const bigNumber: bigint = 100n;
const anotherBig: bigint = BigInt(9007199254740991);

symbol

TYPESCRIPT
// 유일한 식별자를 만들 때 사용
const id: symbol = Symbol('id');
const anotherId: symbol = Symbol('id');
// id !== anotherId — 같은 설명이어도 다른 값

배열(Array)

배열 타입을 선언하는 방법은 두 가지입니다.

TYPESCRIPT
// 방법 1: 타입[] (권장)
const numbers: number[] = [1, 2, 3];
const names: string[] = ['홍길동', '김철수'];

// 방법 2: Array<타입> (제네릭 문법)
const scores: Array<number> = [90, 85, 100];

두 방법은 완전히 동일합니다. 다만 타입[] 형태가 더 짧고 널리 쓰입니다.

TYPESCRIPT
// 배열 요소 타입이 맞지 않으면 에러
const mixed: number[] = [1, 2, '3']; // ❌ Error

// 여러 타입을 허용하려면 유니온 사용
const mixedOk: (number | string)[] = [1, '2', 3];

읽기 전용 배열

TYPESCRIPT
// 수정 불가능한 배열
const readonlyNumbers: readonly number[] = [1, 2, 3];
// readonlyNumbers.push(4); // ❌ Error: Property 'push' does not exist

// ReadonlyArray 제네릭으로도 가능
const readonlyNames: ReadonlyArray<string> = ['홍길동'];

튜플(Tuple)

튜플은 요소의 개수와 각 위치의 타입이 고정된 배열 입니다. JavaScript에는 없는, TypeScript만의 타입입니다.

TYPESCRIPT
// [string, number] 순서와 개수가 고정
const person: [string, number] = ['홍길동', 25];

// ❌ 순서가 다르면 에러
// const wrong: [string, number] = [25, '홍길동']; // Error

// ❌ 개수가 다르면 에러
// const wrong2: [string, number] = ['홍길동']; // Error

튜플의 함정 — push가 된다?

TYPESCRIPT
const tuple: [string, number] = ['hello', 42];
tuple.push('extra'); // ❌ 컴파일 에러가 안 남!
console.log(tuple);  // ['hello', 42, 'extra']

공부하다 보니 여기서 많이 헷갈렸습니다. 타입 검사에서 push를 막지 못하는 것은 TypeScript의 알려진 한계입니다. readonly 튜플을 쓰면 이 문제를 방지할 수 있습니다.

TYPESCRIPT
const safeTuple: readonly [string, number] = ['hello', 42];
// safeTuple.push('extra'); // ❌ Error: Property 'push' does not exist

튜플 활용 — 구조 분해 할당

TYPESCRIPT
// React의 useState가 대표적인 튜플 반환 예시
function useState<T>(initial: T): [T, (newValue: T) => void] {
  let value = initial;
  const setValue = (newValue: T) => { value = newValue; };
  return [value, setValue];
}

const [count, setCount] = useState(0);
// count: number, setCount: (newValue: number) => void

선택적 요소와 나머지 요소

TYPESCRIPT
// 선택적 튜플 요소
type OptionalTuple = [string, number?];
const a: OptionalTuple = ['hello'];      // OK
const b: OptionalTuple = ['hello', 42];  // OK

// 나머지 요소 (Rest Element)
type StringNumberBooleans = [string, number, ...boolean[]];
const c: StringNumberBooleans = ['hello', 1, true, false, true];

타입 표기 vs 타입 추론

TYPESCRIPT
// 명시적 타입 표기
const explicit: string = 'hello';

// 타입 추론 — TypeScript가 알아서 string으로 추론
const inferred = 'hello'; // string이 아닌 'hello' 리터럴 타입으로 추론 (const이므로)
let inferred2 = 'hello';  // string으로 추론 (let이므로)

모든 변수에 타입을 명시할 필요는 없습니다. TypeScript의 타입 추론이 충분히 정확한 경우에는 타입 표기를 생략해도 됩니다. 다음 편에서 타입 추론을 자세히 다룹니다.

정리

타입설명예시
string문자열'hello'
number숫자 (정수/소수 구분 없음)42, 3.14
boolean참/거짓true, false
number[]숫자 배열[1, 2, 3]
[string, number]튜플['hello', 42]
  • 배열 타입은 타입[]Array<타입> 두 가지 표기가 가능하다
  • 튜플은 요소의 개수와 순서가 고정된 배열이다
  • 튜플의 push 허용은 TypeScript의 한계이니 readonly를 활용하자
  • 타입 추론이 정확하면 명시적 타입 표기를 생략해도 된다
댓글 로딩 중...