[타입스크립트 (2)] Type -1

SeHoony·2021년 9월 24일
2

TypeScript

목록 보기
2/7
post-thumbnail

이번 시간은 TypeScript의 꽃, 'Type'이다.
[타입스크립트 (1)]을 간단히 요약하자면, TypeScript는 1) 컴파일 시 에러 체크, 2) Type, 3) OOP(객체 지향 프로그래밍), 이 세 가지가 핵심이다. 여기서 첫 번째는 개념으로 [타임스크립트 (1)]에서 다루었고, 이번 스크립팅에서는 두 번째 Type을 다룬다.

1. 개괄

Type을 공부할 때, 1) Type 자체2) Type 활용을 나누어서 생각해보면 쉽다.

1) Type은 primitive typenew type(편의상)으로 나뉜다.
전자에는 number, string, boolean, null, undefined, symbol 등이 있다. 후자에는 unknown, any, void, never 등 TypeScript에서 새로 나온 Type들이 있다.

그리고 그러한 원재료(Type)를 활용하기 위해 function, array, type Allias, union, intersection 등이 나오게 된다.

즉, 원재료인 Type이 존재하고, 그것을 활용하여 타입을 다양하게 만들기도 하고, 코드의 재사용성 및 기능성을 향상시키기도 하는 것이다.


2. Type

1. Primitive Type(원시 타입)

: number, string, boolean, symbol, null, undefined

const text : string = "txt";
const num : number = 6;

*TIP : null과 undefined의 경우, 약간 다르게 적어준다.

const empty: string | null = null;
const empty2: string | undefined = undefined;

2. new Type(TypeScript에서 추가된 타입) ⁉️

unknown, any, void, never

1) unknown, any : 어떤 Type이든 Okay!
2) void : 아무것도 return하지 않는다.
3) never : 리턴이 전혀 안된다.


3. Type Utilize(타입 활용)

: 타입 활용은 Type 자체와 구분지어 머리에 좀 더 잘 구조화되기 위해 만든 개념이다. 유의하자!

1) function

function getName(name: string) : void {
    console.log(`나의 이름은 ${name}이다`);
}

* TIP : parameters

1) Optional Parameter(?)

function getBody(face:string, hands : number, foots : number, waist? : string){
    ... console.log() ...
}
getBody("face", 2, 2, "waist") => 가능
getBody("face", 2, 2) => 가능

2) default parameter(=)

function getBody(face="round face"){
      console.log(face)
  }
  getBody() => "round face"

3) rest parameter(...)

function getBody(...parts:string[]){
      ... console.log(parts) ...
  }
getBody("face", "hands", "foots"); => ['face', 'hands', 'foots']

2) Array

const fruits : string[] = ["pears", "banana", "strawberry"];

3) Type Alias

: 새로운 Type을 정의하다

// -
type text = string;
type num = number;
const name : text = "sehoon";
// -
type Student = {name : string;age : number;}
const student : Student = {"sehoon", 27}

// - 
// type 대신 값을 넣어줄 수도 있다. 이는 type보다 더욱 한정적으로 type을 제한하는 개념으로 보면 좋을 거 같다.
// 그리고 이 후 Union과 각별한 사이가 된다.
type Name = "name"
type Bool = true;
const sehoon : Name = "name"
const bool : Bool = true;

4) Union(or) & Intersection(and)

1_ Union (|)

// 1. 가위, 바위, 보 게임
type Game = "가위" | "바위" | "보";

function playGame(card:Game):void{
	console.log(card);
}

// 2. 로그인
type Success = {
	res : "success",
    data : {
    	id : "sehoon123",
        pwd : "1234"
    }
}

type Fail = {
	res : "fail",
    data:{}
   }
   
type LoginState = Success | Fail;

function Login(id : string, pwd : string) : LoginState{
	if(id == "sehoon123" && pwd == "1234"){
    	return {res : "success", ....}
    } 
        else{res : "fail", ....}
  }

2_ Intersection (&)

type a = {
	name : string;
    height : number;
}

type b = {
	weight : number;
    fitness=()=> void
}

type Person = a & b => {name : "sehoon", height : 180, weight : 85, fitness =()=>{}}

5) Assertion

: 타입을 강요하는 것. 이 타입이 확실할 때 사용 가능!
: As, <>, !

// - as
function str(): any {
	return "hello"
}
const res = str();
console.log((res as string).length)

// - <>
function str(): any {
	return "hello"
}
const res = str();
console.log(<string>res.length)

4. Conclusion!

지금까지 기본 Type에 대해서 배웠다. Type을 머리에 넣을 때는, Type 그 자체와 Type의 활용으로 나눠 구조화해서 기억하는 것이 좋을 거 같다.

Type은 primitive type(number, string...)와 new Type(never, void, unknown, any) 등이 있고,이를 function, array, type alias, union, intersection 등을 통해 활용할 수 있다.

profile
두 발로 매일 정진하는 두발자, 강세훈입니다. 저는 '두 발'이라는 이 단어를 참 좋아합니다. 이 말이 주는 건강, 정직 그리고 성실의 느낌이 제가 주는 분위기가 되었으면 좋겠습니다.

0개의 댓글