JavaScript/TypeScript

Typescript 기본 타입 정리 (primitive types)

kohi ☕ 2023. 1. 5. 01:39

string, number, boolean


  • string
    • "Hello, World!"
  • number
    • 29, Infinity, NaN
  • boolean
    • true, false

 

object


  • object
    • 속성(Property)
    • 키(Key), 값(Value)
interface PersonType {
    name: string;
    age: number;
    isStudent: boolean;
    studentNum?: number;
}

const person:PersonType = {
    name: "박주경",
    age: 27,
    isStudent: true
}

const getPersonAge = (person: PersonType) => {
    console.log(person.age)
}

 

array, tuple, enum


  • array
    • string[], Array<string>
  • tuple
    • 길이와 타입이 고정된 배열
    • [string, number, number]
const array1:string[] = ["a", "b", "c"];
const array2:number[] = [1, 2, 3];
const array3:(boolean | string)[] = [true, "true"]

let tuple:[string, number, number] = ["hello", 10, NaN]
tuple.push(100);
console.log(tuple); // 아무 오류 없이 push 되므로 주의

 

  • enum
    • enumeration의 약자
    • 이름이 있는 상수들이 열거되어 있는 집합
enum BloodType {
    A,
    B,
    O = 200
    AB
}

const myBloodType = BloodType.B;
const herBloodType = BloodType.AB;
console.log(myBloodType); // 1
console.log(herBloodType); // 201

 

any, void, never


  • any
    • any 타입의 변수에는 어떤 타입의 값이든 할당 가능
    • 사용하지 않는 것이 좋다
    • noImplicitAny 설정

 

  • void
    • 어떤 타입도 존재할 수 없음
    • 함수에서 리턴 값이 없을 때 사용
const sum = (a:number, b:number):void => {
    // 리턴값이 없음
    console.log('void')
}

 

  • never
    • 어떠한 값도 가질 수 없는 타입
    • 공집합

 

null, undefined


  • null, undefined
    • strictNullChecks 옵션 false인 경우
      1. 모든 타입의 변수에 null과 undefined를 대입 가능
      2. 런타임에 예기치 않은 오류가 발생할 수 있음
    • strictNullChecks 옵션 true인 경우(권장)
      1. null과 undefined일 수 있는 변수를 참조하려고 하면 에러 발생

 

symbol


  • symbol
    • ES6에 새롭게 추가된 number나 string과 같은 기본 데이터 타입 (원시 타입)
    • 변경 불가능한 유일한 값

 

unknown


  • unknown
    • 단어 그대로 타입이 뭔지 알 수 없는 타입
    • 어떤 값이든 들어올 수 있으니 엄격하게 검사해서 사용해라!
    • any 타입과 유사하지만 훨씬 안전하다
    • 타입을 특정해 주기 전까지는 무언가 수행하려고 할 때 에러를 내 준다

function f1(a: any) {
    a.toUpperCase();
}

function f2(a: unknown) {
    if(typeof a === "string") {
        return a.toUpperCase();
    } else {
        return "문자열이 아닙니다."
    }
} // 좀 더 상세하게 작성