TypeScript의 데이터 타입

TypeScript의 데이터 타입

이 글은 TypeScript의 데이터 타입을 설명합니다.

YouTube Video

TypeScript의 데이터 타입

TypeScript는 다양한 데이터 타입을 제공합니다. 이를 통해 변수, 함수 인자, 반환 값에 대해 엄격한 타입을 정의할 수 있습니다. 아래는 주요 데이터 타입과 그 사용법입니다.

기본 타입

number 타입

1let age: number = 25;
2console.log(age);          // Outputs: 25
3console.log(typeof age);    // Outputs: number
  • number는 정수와 부동 소수점 숫자(소수 포함)를 포함한 숫자 값을 처리하기 위해 사용되는 타입입니다. 특정 한계를 초과하는 값을 처리하면 Infinity 또는 NaN(Not-a-Number)이 결과로 나타납니다.
1// Decimal calculations
2console.log(0.1 + 0.2 === 0.3); // false
3console.log(0.1 + 0.2); // 0.30000000000000004
4
5// Calculations with large numbers
6console.log(9007199254740991 + 1); // correct value
7console.log(9007199254740991 + 2); // incorrect value
  • TypeScript에서는 숫자가 부동 소수점 숫자로 표현됩니다. 이는 계산 결과에 약간의 부정확성을 초래할 수 있습니다.

  • 금액 계산과 같이 정밀한 계산이 필요한 경우 이러한 반올림 오류를 피해야 합니다. 예를 들어, BigInt 또는 toFixed()를 사용하거나 decimal.js와 같은 라이브러리를 사용하여 소수 자릿수를 조정할 수 있습니다.

string 타입

string 타입은 텍스트 데이터를 처리합니다.

1let greeting: string = "Hello, TypeScript!";
2console.log(greeting);     // Outputs: Hello, TypeScript!
3console.log(typeof greeting);  // Outputs: string

boolean (논리 타입)

boolean 타입은 두 가지 값: true 또는 false를 가집니다.

1let isOpen: boolean = true;
2console.log(isOpen);       // Outputs: true
3console.log(typeof isOpen);    // Outputs: boolean

null과 undefined

null은 '존재하지 않는 값'을, undefined는 '정의되지 않은 값'을 나타냅니다.

1let emptyValue: null = null;
2let notDefined: undefined = undefined;
3
4console.log(emptyValue);       // Outputs: null
5console.log(typeof emptyValue);    // Outputs: object (JavaScript specification)
6
7console.log(notDefined);       // Outputs: undefined
8console.log(typeof notDefined);    // Outputs: undefined

Array

TypeScript에서는 배열 요소의 타입을 지정할 수 있습니다. number[]는 숫자 배열, string[]는 문자열 배열입니다.

1let numbers: number[] = [1, 2, 3, 4];
2console.log(numbers);        // Outputs: [1, 2, 3, 4]
3console.log(typeof numbers); // Outputs: object
4
5let words: string[] = ["TypeScript", "JavaScript"];
6console.log(words);          // Outputs: ["TypeScript", "JavaScript"]
7console.log(typeof words);   // Outputs: object

튜플

튜플은 서로 다른 타입의 요소들로 구성된 배열입니다.

1let person: [string, number] = ["Alice", 30];
2console.log(person);         // Outputs: ["Alice", 30]
3console.log(typeof person);  // Outputs: object

열거형 (Enum)

enum은 이름이 지정된 상수 집합을 정의합니다.

1enum Color {
2    Red,
3    Green,
4    Blue
5}
6
7let favoriteColor: Color = Color.Green;
8console.log(favoriteColor);  // Outputs: 1 (Defaults start from 0)
9console.log(typeof favoriteColor); // Outputs: number

any

any 타입은 어떤 타입의 값도 가질 수 있으며 타입 검사를 비활성화하려는 경우 사용됩니다.

1let anything: any = "Hello";
2console.log(anything);       // Outputs: Hello
3console.log(typeof anything);    // Outputs: string
4
5anything = 42;
6console.log(anything);       // Outputs: 42
7console.log(typeof anything);    // Outputs: number

유니온 타입

유니온 타입을 사용하여 여러 타입 중 하나를 가질 수 있는 변수를 정의할 수 있습니다.

1let identifier: number | string = "ID_12345";
2console.log(identifier);     // Outputs: ID_12345
3console.log(typeof identifier);  // Outputs: string
4
5identifier = 12345;
6console.log(identifier);     // Outputs: 12345
7console.log(typeof identifier);  // Outputs: number

요약

  • number, string, boolean: 기본 타입.
  • null, undefined: 특수 값.
  • Array: 타입 주석이 포함된 배열.
  • Tuple: 서로 다른 타입의 요소를 가진 배열.
  • enum: 열거형 타입.
  • any: 어떤 타입이든 사용할 수 있는 타입.
  • Union: 여러 타입 중 하나의 값을 가질 수 있는 변수.

이 데이터 타입들을 사용함으로써 TypeScript는 타입 안정성을 강화하여 개발 중 오류를 예방하기 쉽게 만듭니다.

래퍼 객체

TypeScript의 래퍼 객체는 기본 데이터 타입을 객체처럼 다룰 수 있도록 자동으로 생성되는 객체입니다. 기본 타입은 가볍고 빠른 작업을 허용하며, 객체 타입에는 메서드와 속성이 있어 더 풍부한 작업이 가능합니다.

JavaScript(와 TypeScript)에서는 string, number, boolean 같은 기본 타입에 해당하는 래퍼 객체가 존재합니다. 이들은 각각 String, Number, Boolean이라는 생성자 함수를 사용해서 생성됩니다.

아래는 래퍼 객체의 예시들입니다.

문자열 객체(String Object)

String 객체는 문자열에 대한 속성과 메서드를 제공합니다.

1let strPrimitive: string = "Hello, World!";
2let strObject: String = new String("Hello, World!");
3
4console.log(strPrimitive);         // Outputs: Hello, World!
5console.log(typeof strPrimitive);  // Outputs: string
6
7console.log(strObject);            // Outputs: [String: 'Hello, World!']
8console.log(typeof strObject);     // Outputs: object

기능:

  • 기본 string 타입과 달리, String 객체는 typeof에 의해 object로 간주됩니다.
  • 래퍼 객체는 문자열을 조작하거나 메서드를 호출할 때 유용합니다.

숫자 객체(Number Object)

Number 객체는 숫자에 대한 속성과 메서드를 제공합니다.

1let numPrimitive: number = 42;
2let numObject: Number = new Number(42);
3
4console.log(numPrimitive);         // Outputs: 42
5console.log(typeof numPrimitive);  // Outputs: number
6
7console.log(numObject);            // Outputs: [Number: 42]
8console.log(typeof numObject);     // Outputs: object

기능:

  • Number 객체는 숫자를 위한 래퍼로서, 숫자 연산을 위한 메서드(예: toFixed)를 포함합니다.

불리언 객체(Boolean Object)

Boolean 객체는 불리언 값에 대한 속성과 메서드를 제공합니다.

1let boolPrimitive: boolean = true;
2let boolObject: Boolean = new Boolean(true);
3
4console.log(boolPrimitive);        // Outputs: true
5console.log(typeof boolPrimitive); // Outputs: boolean
6
7console.log(boolObject);           // Outputs: [Boolean: true]
8console.log(typeof boolObject);    // Outputs: object

기능:

  • Boolean 객체는 기본 boolean 타입의 래퍼로서, object로 간주됩니다.

래퍼 객체와 기본 타입의 차이점

래퍼 객체는 객체로 간주되기 때문에 약간의 성능 저하가 발생하지만, 추가된 속성과 메서드 덕분에 더 많은 기능적 작업이 가능합니다. 또한, =====를 사용한 비교에서도 차이가 있습니다.

1let numPrimitive: number = 123;
2let numObject: Number = new Number(123);
3
4console.log('==  : ', numPrimitive == numObject);  // Outputs: true (Value comparison)
5console.log('=== : ', numPrimitive === numObject); // Outputs: false (Due to differing types)

기능:

  • ==는 값을 비교하지만, ===는 타입까지 엄격히 비교합니다. ===는 래퍼 객체와 원시 타입을 비교할 때 false를 반환합니다.

타입 변환

TypeScript에서는 암시적명시적 타입 변환을 적절히 관리하는 것이 중요합니다.

암시적 타입 변환

  • TypeScript에서는 타입 안전성을 보장하기 위해 암시적 타입 변환을 가능한 한 피하는 것이 좋습니다.
1const result: string = 5 + "5"; // "55" (the number is converted to a string)
2
3console.log(result);
  • 이 예에서는 숫자 5가 암시적으로 문자열로 변환되어 문자열 "55"이 생성됩니다.

명시적 타입 변환

  • TypeScript에서는 타입 주석이나 타입 변환 함수를 사용하여 안전하게 타입 변환을 수행하십시오.
1const num: string = "123";
2const convertedNum: number = Number(num); // Converts "123" to the number 123
3
4console.log(typeof num);
5console.log(typeof convertedNum);
  • 이 예에서는 Number() 함수를 사용하여 문자열 "123"을 명시적으로 숫자 123으로 변환합니다.

타입 검사

TypeScript에서는 typeof 연산자를 사용하여 변수의 데이터 타입을 확인할 수 있습니다.

 1// Output: The type of 42 is: number
 2console.log('The type of 42             is:', typeof 42);
 3
 4// Output: The type of 42 is: bigint
 5console.log('The type of 42n            is:', typeof 42n);
 6
 7// Output: The type of "hello" is: string
 8console.log('The type of "hello"        is:', typeof "hello");
 9
10// Output: The type of true is: boolean
11console.log('The type of true           is:', typeof true);
12
13// Output: The type of undefined is: undefined
14console.log('The type of undefined      is:', typeof undefined);
15
16// Output: The type of null is: object
17console.log('The type of null           is:', typeof null);
18
19// Output: The type of Symbol() is: symbol
20console.log('The type of Symbol()       is:', typeof Symbol());
21
22// Output: The type of {} is: object
23console.log('The type of {}             is:', typeof {});
24
25// Output: The type of function () {} is: function
26console.log('The type of function () {} is:', typeof function () {});
  • TypeScript에서는 타입 확인에 typeof를 사용할 수 있지만, 보다 정밀한 타입 확인을 위해 instanceof 또는 is 연산자를 사용하는 것도 권장됩니다.

요약

  • 래퍼 객체는 원시 타입에 추가 메서드와 속성을 제공하기 때문에 객체로 간주됩니다.
  • String, Number, Boolean이 래퍼 객체의 대표적인 예입니다.
  • 원시 타입과 달리, 래퍼 객체는 typeof에 의해 object로 식별됩니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video