JavaScript에서 TypeScript로 기초
Why TypeScript?
자바스크립트를 쓰다가 타입스크립트를 쓸 때, 가장 좋은 장점은 예기치 못 한 오류를 잡기 편하다는 것 이다. 값의 타입을 설정하기 때문에 실수로 다른 키값에 다른 종류의 값을 넣었을 때 오류를 띄워준다. 한 가지 예시로 interface 선언을 통해서 객체의 key와 value의 타입을 설정하면 const 로 선언한 변수명 뒤에 ':'를 붙여서 적용할 수 있다.
const user = {
name: "Hayes",
id: 0,
};
----------------------------------------
interface User {
name: string;
id: number;
}
//위와 같이 interface를 선언한 이후에 아래와 같이 사용할 수 있다.
const user: User = {
name: "Hayes",
id: 0,
};
그리고 타입스크립트 또한 객체지향적인 언어이기 때문에 interface를 class에서도 적용할 수 있다. 또 함수의 인자나 리턴 값에도 주석으로 interface를 사용할 수 있다. ex) function getAdminUser(): User { ... } // function deleteUser(user: User) { ... }
interface User {
name: string;
id: number;
}
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: User = new UserAccount("Murphy", 1);
자바스크립트에도 이미 boolean, bigint, null, number, string, symbol, object, and undefined 등의 기초적인 형식이 있기 때문에 타입스크립트에서는 이 형식에서 확장하여 any(모든 것을 허용), unknow(타입을 사용하려는 사람이 어떤 타입인지를 확실시 해줘야한다), never( 다른 모든 타입을 제외한 일어날 수 없는 타입조건), void(undefined 나 리턴 값이 없는 함수) 등을 추가해준다고 생각하면 된다.
Type 과 Interface
이 부분에 대해서는 영문의 playground 코드를 번역했다. 결론적으로 interface가 type보다 확정하기도 더 용이하고, 오류에 있어서도 더 자세한 설명이 나오기 때문에 interface를 사용하길 더 권장하고 있다.
// T객체를 선언할 때는 주로 interfaces, type 2가지 툴을 사용합니다.
// 이 둘은 굉장히 비슷하고 또 대부분의 상황에서 똑같이 작동됩니다.
type BirdType = {
wings: 2;
};
interface BirdInterface {
wings: 2;
}
const bird1: BirdType = { wings: 2 };
const bird2: BirdInterface = { wings: 2 };
// 타입스크립트는 'structural type system' 이기 때문에
// 둘을 섞어 사용하는 것도 가능합니다.
const bird3: BirdInterface = bird1;
// 둘은 서로를 확장하는데 도움을 줍니다. 'Type'은 교차 유형을 통해 작업을 수행하는 반면
// 'Interface'는 키워드를 가집니다.
type Owl = { nocturnal: true } & BirdType;
type Robin = { nocturnal: false } & BirdInterface;
interface Peacock extends BirdType {
colourful: true;
flies: false;
}
interface Chicken extends BirdInterface {
colourful: false;
flies: false;
}
let owl: Owl = { wings: 2, nocturnal: true };
let chicken: Chicken = { wings: 2, colourful: false, flies: false };
// 'type'보다 'interface'를 사용하는 것이 좋습니다.
// 왜냐면 오류가 더 잘 나타나기 때문입니다.
// 마우스를 올렸을 때 따라오는 오류 메시지를 본다면(블로그에서는 따로 이미지를 첨부하겠습니다),
// 타입스크립트가 얼마나 간결하고 집중도 높은 오류메시지를 주는지 'Chicken'
// ineterfaces를 통해서 볼 수 있습니다.
owl = chicken;
chicken = owl;
// 타입 별칭과 인터페이스 사이 한 가지 큰 차이점은
// 인터페이스는 열려 있고 타입 별칭은 닫혀 있다는 것입니다.
// 이는 인터페이스를 다음에 선언할 때 내용을 더 확장할 수 있음을 의미합니다.
interface Kitten {
purrs: boolean;
}
interface Kitten {
colour: string;
}
//이와 달리 타입은 한 번 선언하면, 선언 밖에서 내용을 바꿀 수 없습니다.
type Puppy = {
color: string;
};
type Puppy = {
toys: number;
};
https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html
Documentation - TypeScript for JavaScript Programmers
Learn how TypeScript extends JavaScript
www.typescriptlang.org