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