(typescript) type의 선언

Youje0·2023년 2월 15일

1. 일반적 변수의 type 선언

일반적인 변수일때

a : number = 1;
b : string = "hello world"
c : boolean = true
d : number[] = [1,2,3]
e : string[] = ["hi","hello",bye]

2. 객체의 type 선언

const example : {
name : string,
age : number
} = {
name : "choi",
age : 18,
}

console.log(example)
// 
{
  "name": "choi",
  "age": 18
} 

3. 함수의 type 선언

   						<-- 인자의 type--> <-- retun의 type-->
const exampleFunction = (name : string) : {name : string} =>{
	return {
    name : name
    }
}

exampleFunction(choi)

4. Type별칭 (Type Alias)

type Player = {
name : string,
age : number
}

const example : Player = {
name : "choi",
age : 18
}

console.log(example) 
// 
{
  "name": "choi",
  "age": 18
} 

5. readonly

readonly는 array 또는 tuple에서만 사용가능

const arr : readonly numer[] = [1,2,3,4,5];
console.log(arr) // [1,2,3,4,5]

if =>
arr.push(6)
console.log(arr) // error arr은 읽기전용(readonly)이기 때문에 push로 추가 할 수 없음!

만약 readonly로 선언된 배열을 바꾸고 싶다면 ?
<-- spread 메소드(...arr)를 사용하여 얕은 복사를 통해 수정이 가능함 -->
const arr2 = [...arr];
arr2.push(6);
console.log(arr2) // [1,2,3,4,5,6]

6. tuple

<-- tuple은 지정한 type의 순서와 갯수가 동일해야한다. -->
const player : [string,number,boolean] = [choi,18,true];

if =>
player[0] = 18; // error player의 0번째 index는 string 타입이 들어가야함.
player.push = 20; // error tuple로 선언된 배열의 갯수는 총 3개이기 때문에 push 사용불가
<-- tuple 또한 readonly의 사용이 가능하며 배열과 똑같이 동작함 -->
const player : readonly [string,number,boolean] = [choi,18,true];

if =>
player[0] = "joy" // error 읽기전용(readonly)이기 때문에 변경 불가.
player.push(6) // error 읽기전용이고 tuple이기 때문에 배열 추가 불가.
  • JS(javascript)엔 readonly와 tuple이 없다.
  • 그렇기 때문에 JS(javascript)에선 readonly와 tuple로 선언한 값도 변경이 가능하다.

7. undefined || null

type example ={
name : string | null,
age : number | undefined
}

위와 같이 null과 undefined을 union type으로 선언 할 수 있는데 위와 같이 선언하면
name은 string이 올수도, null이 올수도있게 되고 age는 number가 올수도 undefined가 올수도 있다.

8. 유니온 타입, 인터섹션 타입

8-1 유니온 타입(Union type)

유니온 타입(Union Type)이란 자바스크립트의 or 연산자 || 와 같은 타입으로 A거나 B거나 둘 중 하나가 만족하면 되는 타입이다.

const example : number | string = 1;
console.log(example) // 1
혹은
const example : number | string = "choi";
console.log(example) // choi

위와 같이 union type으로 선언했을땐 둘 중 하나만 만족해도 에러없이 실행된다.

interface Person1 {
    name: string;
    age: number;
}

interface Person2 {
    name: string;
    place: string;
}

const exmaple : Person1 | Person2 = {
   name : "choi",
   age : 18,
   place : "home"
}

console.log(exmaple) 
// 
{
  "name": "choi",
  "age": 18,
  "place": "home"
} 

9. any type

any는 말그대로 어떠한 타입도 될 수 있으며 어떠한 값을 넣어도 error 없이 출력된다.
any를 사용하면 Typescript를 사용하는 의미가 없기 때문에 사용을 지양해야한다.

const example : any = 1;
console.log(example) // 1

const example1 : any = "choi";
console.log(example1) // choi

const example1 : any = true;
console.log(example1) // true

const example2 : any = [1,2,3,4,5];
console.log(example1) // [1,2,3,4,5]

const example2 : any = [1,2,3,4,5];
console.log(example1) // [1,2,3,4,5]

const example3 : any = {name : "choi"};
console.log(example2) // name : "choi"

10. unknown

unknown 타입은 API로부터 응답을 받을때 그 응답의 타입을 모르면 unknown 타입을 사용 할 수 있다.

let a : unknown;

let b = a + 1; // a가 unknown type이기 때문에 error 발생

if =>

let a : unknown;
<-- if문으로 a의 타입을 확인 시켜줬기 때문에 TS에선 오류로 보지않음. -->
if(typeof a === "number"){
	let b= a + 1 
}

if(typeof a === "string"){
	let b = toUpperCase();
}

위의 코드가 동작하는 이유는 a가 number여야만 실행되는 코드이기 때문에 TS에서 오류로 보지않음
만약 else도 작성한다면 else문이 실행된다.

11. void

void는 함수에서만 작동하는 type이다.

const example () : void =>{
	console.log("hello world")
}

위와 같이 return이 없는 함수에 선언하는 type인데 대개 void를 따로 선언하지 않아도
typescript에서 기본적으로 선언하기 때문에 직접 선언할 필요는 없다.

<--  코드는  코드와 같은 코드이다. void가 없어도 void가 선언 되어있다. -->
const example ()  =>{
	console.log("hello world")
}

12. call signatures

call signatures란 ?

  • 빨간색 부분을call signatrues라고 한다.
<-- call signatures 활용 -->

type Add = (a:number,b:number) => number;

const add : Add = (a,b) => a+b;

위와 같이 type에 인자의 타입과 함수가 어떻게 작동할지 서술해 둘 수 있다.

13. over loading

overloading은 함수가 여러개의 call signatures가 있는 함수이다.

<-- overloading 활용 -->
type Add = {
(a:number,b:number) : number;
(a:number,b:sring) : number;
}

const add : Add = (a,b) =>{
	if(typeof b === number)
    	return a
    else 
    	return a+b
}
<-- 만약 인자의 갯수가 다를때 -->
type Add = {
(a:number,b:number) : number;
(a:number,b:number,c:number) : number;
}

const add : Add = (a,b,c? : number) =>{
   if(c) return a+b+c
	return a + b
}

인자 c에 ?를 붙여 c의 type을 number | undefined로 선언해주고 c가 true일때만 c를 사용한다. 

참고 : 노마드코더 TS 강의
https://nomadcoders.co/typescript-for-beginners/lobby

profile
ㅠㅠ

0개의 댓글