TS | TypeScript의 Type엔 뭐가 있나?!

imzzuu·2022년 4월 28일

강의를 듣는데 "타입스크립트엔 이런 타입이 있는데, 이 타입에 타입은 이렇게 쓰고 이 타입은"
이거 무슨 라임도 아니고 게슈탈트 붕괴를 경험했다고한다... 그럼 포스팅 시작!

TypeScript란?


  • JS 에 Type 을 얹은 프로그래밍 언어
  • 컴파일 언어 (or Traspile 언어)
  • TS 작성 → TS 컴파일러 → Plain JS | 따라서 ts 컴파일러 설치 필요

🧊 TypeScript 컴파일러 commend

tsc 파일명 : js 파일로 컴파일 됨
nano 파일명 : ts 파일 생성
$npm init -y : node 환경으로 만들어주기
$npm i typescript -D : ts 설치
$npx tsc --init : tsconfig.json 생성

"scripts": {
    "build": "tsc"
  },

node_modules/.bin/tsc 를 매번 입력해서 컴파일 하기 번거롭기 때문에 수정!

$ tsc -w : tsc 명령어를 매번 실행하지 않더라도 tsc -w (watch)모드는 자동으로 컴파일됨
$node 파일명 : 터미널에서 실행 결과 보기

🧊 Type Annotation

  • Annotation 은 주석이라는 사전적 의미를 갖는다.
  • 타입 스크립트에서는 특정한 변수 등에 Type 을 지정해주는 일을 한다.
let a : number
let b = string
function hello(c:number){
}

b = 36  // => 에러남 string만 들어갈 수 있음

🧊 TypeScript 의 데이터 타입

JS 의 기본 자료형 6가지

  • Boolean
  • Number
  • String
  • Null
  • Undefined
  • Symbol

object 자료형

  • Array : object 형

프로그래밍을 도울 추가 타입 (안정성)

  • Any, Void, Never, Unknown
  • Enum
  • Tuple : object 형

1. Primitive Type

  • 오브젝트와 레퍼런스 형태가 아닌 실제 값을 저장하는 자료형
  • lliteral값을 Primitive Type의 서브 타입으로 나타낼 수 있다.
  • 또는 래퍼 객체로 만들 수 있다.

래퍼 객체 예시

new Boolean(false) // typeof => object
new String('world') // typeof => object

이렇게 만들면, 원시 타입이 아닌 객체가 됨 ⇒ 타입 스크립트에선 타입으로 사용하는 것은 지양! ⇒ 소문자로 타입을 지정해야함!!!!

1) Boolean

let isDone: boolean = false;
isDone = true;
console.log(typeof isDone); // boolean

let isOk: Boolean = true; // 리터럴로 사용하기!
let isNotOk: boolean = new Boolean(true); // 사용 x

2) Number

let decinal: number =6 // 10진수

let hex: number = 0xf00d // 16진수

let binary: number = 0b1010 // 2진수

let octal: number = 0o744 // 8진수

let notANumber:number = NaN

let underscoreNum: number = 1_000_000

3) String

let name: string = "Mark" // 일반 문자열

let fullName: string = `Mark Lee` // 백틱 리터럴 방식
let age: number = 39

let sentence: string = `Hello, My name is ${fullName}.

I'll be ${age+1} years old nex month.` // 리터럴 방식도 지원! 

4) Symbol

  • 원시 타입의 값을 담아서 사용
  • 고유하고 수정 불가능한 값으로 만들어준다.
  • 그렇기 때문에 주로 접근을 제어하는데 쓰이는 경우가 많다.
  • new Symbol로 사용 불가
  • symbol 을 함수로 사용해서 symbol 타입을 만들어낼 수 있다.
console.log(Symbol("foo")===Symbol('foo')); // false

const sym = Symbol()
const obj = {
    [sym] :"value"
}
// obj["value"] 안돼! 
obj[sym] // 이렇게 접근하기! 

5) Null & Undefined

  • null 은 null 만, undefined 는 undefined 만 할당 가능
  • 다른 타입에 넣어두고 싶다면, union 타입으로 작성 ( | )
let n:null =null // typeof => object
let u:undefined = undefined // typeof => undefined

let myName: string = null // 불가
let u: undefined = null // 불가

let union: string | null = null // union 타입으로 작성하면 가능

2. Object Type

  • 원시 타입이 아닌 것을 나타내고 싶을 때 사용하는 타입

1) Object

declare function  create(o:object | null) : void

주로 이렇게 사용하며, 원시 타입은 받지 않을거야! (오류 냄)

2) Array

비슷한 요소들을 모아 보관할 때 사용

let list: number[] = [1,2,3]; // 주로 이걸 많이 씀
let arra:Array<number> = [1,2,3];
let list:(number|string)[] = [1,2,3,"4"];

3. 그 외

1) Tuple

  • 같은 순서에 같은 타입만 할당 가능
  • 길이도 제한됨
let x:[string, number]

 x=["hello", 39]

 x=[36,"hello"] // 불가
 x[3] = "world" // 불가 (length 가 1 까지라서 할당 불가)

// 구조분해할당
const person: [string, number] = ["Mark", 39]
const [first, second] = person

2) Any

  • 어떤 것이든 들어올 수 있다.
  • 모르는 동적인 변수의 Type에 지정
  • 개체를 통해 전파되기 때문에 편의를 위해 사용한다면 안전성이 떨어진다.
function returnAny(message: any):any {
     console.log(message)
 }

 const any1 = returnAny("리턴은 아무거나");

 any1.toString();

any 로 지정해서 전파되는 것을 방지하기 위해 안쪽에서 타입을 지정해주면, 그 이후로는 any가 아닌 number가 된다.

function leakingAny(obj:any){
     const a:number = obj.num;
     const b= a+1;
     return b
 }

 const c = leakingAny({num:0})
 c.indexOf("0") // number 타입이기때문에 오류남!

하지만, 이렇게 사용하는 것보다 unkonwn 을 많이 사용함.

3) Unknown

  • 모르는 동적인 변수의 Type에 지정
  • any의 안전성을 보완한 type
declare const maybe: unknown

 const aNumber: number = maybe // 오류 (바로 할당 불가)

// 타입가드 방법
 if(maybe === true ){
     const aBoolean: boolean = maybe // true
 }

 if(typeof maybe === 'string'){
    const aString: string = maybe // string 
 }

4) Never

  • 모든 타입의 서브 타입
  • 그 어떤 것도 할당 할 수 없다.
  • 잘못된 타입을 넣는 실수를 막고자 할 때 사용
function error(message:string):never{
    throw new Error(message)
 }

 function fail(){
     return error("failed")
 }

 function infiniteLoop():never{
     while(true){}
 }

잘못된 타입을 넣는 실수를 막을 때 예제

let a: string ="hello"
 if(typeof a !== "string"){
     a; 
// never (string 인데, string 이 아닌 건 아무 것도 할당 할 수 없는 상태)   
 }

let b: string | number ="hello"
 if(typeof b !== "string"){
     b; // string 일 땐 never, number 일 때만 실행

 }

5) Void

함수의 return 값으로 아무 것도 사용하지 않는다고 명시하는 것

function returnVoid(message:string){ // viod
     console.log(message)
     return 
 }

 const r = returnVoid('리턴이 없다.') // viod

0개의 댓글