type allias

Typescript에서는 type도 따로 선언할 수 있다. 길고 복잡한 Union type을 따로 type allias로 만들어 사용하여 가독성 향상시키고 코드 길이를 줄일 수 있다. 

type 변수의 이름은 첫 글자를 대문자로 하는게 국룰

!! type은 재정의가 불가능하다 !!

type Person = { name : string, age : number };
let minseo : Person = { name : Minseo, age : 21 };

 

type extend

type Name = { name : string };
type Age = { age : number };

type Person = Name & Age;

let Minseo : Person = { name : Minseo, age : 21 };

 

function type allias

함수 type allias는 함수 표현식에만 사용할 수 있다.

type FunctionType = ( a : string ) => number; 
// string type의 매개변수를 갖고, return type이 number인 함수 type allias

let myFunction : FunctionType = function(){
	// 함수 표현식
}

object 내의 함수도 함수 type allias를 지정할 수 있다. 

type Member = {
	name : string,
    age : number,
    plusOne : ( x : number ) => number,
    changeName : () => void
}

 

728x90

'Language > Typescript' 카테고리의 다른 글

[ Typescript ] rest parameter type지정  (2) 2021.12.18
[ Typescript ] interface  (0) 2021.12.18
[ Typescript ] class type 지정  (0) 2021.12.18
[ Typescript ] Litertal Types & as const  (2) 2021.12.17
[ Typescript ] Typescript 시작하기  (0) 2021.12.17

Typescript

Typescript는 type을 명시하지 않는 Javascript 문법에 type이 추가된 언어로, 1 + "3"과 1 + 3의 결과 값이 같은 Javascript와 달리 Typescript에서는 type을 검사하여 error message를 띄워준다. 

 

install

# global install
$ npm i typescript -g

# local install
$ npm i typescript --save-dev

Type

1. primitives : string, number, boolean

2. Array

3. any

 - any type의 경우 특정 값으로 인해 type check error가 발생하는 것을 원하지 않을 경우 마다 사용할 수 있는 특수 타입으로 모든 type을 할당 할 수 있다. => typescript을 사용하는 의미가 없어지게 된다. 

type 관련 버그를 잡아주지 않는다.

let obj : any = { x: 0 } ;

obj.foo();
obj();
obj.bar = 100;
obj = "hello";
const n : number = obj;

4. Object

let student : { name : string, grade : number } = {
	name : "kitez",
    grade : 3
};

console.log(student); // { name : "kitez", grade : 3 }

5. void

void는 return값이 없는 함수에서 return type으로 사용된다. return 값이 없는 함수는 undefined를 반환한다.

function a() : void{
	console.log("a");
}

console.log(a()); // undefined

6. Union

Union은 type을 2개 이상 합친 새로운 type을 말한다.

let id : number | string = 123;
id = "123";
id = 456;
// type이 number or string 가능

7. unknown

any와 같이 모든 자료형을 허용해주나, any보다 안전하다. 왜냐하면 any의 경우 아래와 같이 다른 type의 변수에 값을 넣어도 error가 발생하지 않지만 unknown의 경우 이러한 type error를 잡아준다.

let name : any;
name = 123;

let name2 : unknown;
name2 = 123;

let name3 : string = name; // error no
let name4 : string = name2; // error yes

Functions

Parameter type

function add(x : number, y : number) : number{
	return x + y;
}

add(2,3); => return 5
# Argument of type 'string' is not assignable to parameter of type 'number'.
add("2",3) => error

 

Return type

function message() : string{
	return "Hello!";
}

message() => return "Hello!"

 

 

 

 

 

출처 :

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html

https://www.digitalocean.com/community/tutorials/typescript-new-project

728x90

+ Recent posts