몇번이나, 정말 몇번이나 티스토리에 타입 스크립트 완벽 정복 이 난리 치면서 글로 똥싸지르다가
지우고 타입 스크립트로 소설 쓴다고(진짜 소설) 또 똥 싸지르고 그러다가 진짜 운 좋아서 투입한 네이버에서 아 내 블로그 봐야지 하고 티스토리 갔다가
눈칫밥먹고 그러다가 어느새 벨로그로 넘어오니 제대로 정리해야겠다 싶더라.
그러니까 또 기억이 안나네?, 해봤으니까 오래 안걸리겠지?
자, 타입스크립트 공홈으로 들어가본다.
원래 같았으면
"스크린샷 찍어놓고 메인에 TypesScript is Javascript with syntax for types ! 가 써져있다!
이 말은 즉슨 타입스크립트는 type를 위한 Javascript 문법이다!
자 여기서부터 하나하나 살펴보자."
OFFICE
if("" == 0) {
// 이거야! 하지만 왜?!
}
if(1 < x < 3) {
// x 에서 결괏값을 찾을거야 어느 타입이든 상관없이 true 인 값들로 !
// True for *any* value of x!
}
뭐 이딴 식으로 기재했을거다.
하지만 이제부턴 차근차근 정리 해보기로 한다.
자 이제 진짜 시작이다.
타입스크립트는 JS를 추상화하기 위한 좀 더 Super Set 언어다.
Example
변수를 생성하면 동시에 특정 값에 할당하는 경우 TypeScript는 그 값을 해당 변수의 타입으로 사용
let helloWorld = "HelloWorld";
// ^?
Javascript는 다양한 디자인 패턴을 가능하게 하는 동적 언어이다. 몇몇 디자인 패턴은 자동으로 타입을 제공하기 힘들 수 있는데(동적 프로그래밍을 사용하고 있을 것 이기 때문에) 이러한 경우에 TypeScript는 TypeScript에게 타입이 무엇이 되어야 하는지 명시 가능한 JavasScript 언어의 확장을 지원한다.
interface Animal {
id: number;
name: string;
}
변수 선언 뒤에 : TypeName 의 구문을 사용해 JavaScript 객체가 새로운 interface의 형태를 따르고 있음을 선언할 수 있다.
interface Animal {
id: number;
name: string;
}
const animal: Animal = {
id: 0,
name: "강아지",
}
interface는 class로도 선언할 수 있다.
interface Animal {
name: string;
id: number;
}
class AnimalAccount {
id: number;
name: string;
constructor(id: number, name: string){
this.id = id;
this.name = name;
}
}
const animal: Animal = new AnimalAccount("말티즈", 1);
inteface는 함수에서 매개변수와 리턴 값을 명시하는데도 사용된다.
interface Animal {
id: number;
name: string;
}
function getAdminAnimal(): Animal {
//
}
function deleteAnimal(animal: Animal){
}
또한 TypeScript는 JavasScript에서 갖고 있는 원시 타입외에 추가적인 Type을 갖고 있다. 이러한 종류에는 any 혹은 unkown, void 이 있다.
TypeScript는 코드 시간에 따라 변수가 변경되는 방식을 이해하면
Type검사를 통해 원하는 Type을 골라낼 수 있다.
function wrapInArray(obj: string | string[]){
if (typeof obj === "string") {
return [obj];
} else {
return obj;
}
}
type StringArray = Array<string>;
type numberArray = Array<number>;
type ObjectWithNameArray = Array<{name: string}>;
interface Backpack<type> {
add: (obj: Type) => void;
get: () => Type;
}
/*
TypeScript에 `backpack`이라는 상수가 있음을 알려준다.
const backpack: Backpack<string>이 어디서 왔는지 걱정할 필요가 없습니다.
*/
declare const backpack: Backpack<string>;
// 위에서 Backpack의 변수 부분으로 선언해서, object는 string입니다.
const object = backpack.get();
// backpack 변수가 string이므로, add 함수에 number를 전달할 수 없습니다.
backpack.add(23);
구조적 타입 시스템에서 두 객체가 같은 형태를 가지면 같은 것으로 간주 된다.
interface Point {
x: number;
y: number;
}
function printPoint(p: Point){
console.log(`${p.x}, ${p.y}`);
}
// "12, 26"를 출력 한다.
const point = { x: 12, y: 26};
printPoint(point);
interface Point {
x: number;
y: number;
}
function printPoint(p: Point){
console.log(`${p.x}, ${p.y}`);
}
const point3 = { x: 12, y:26, z:89};
printPoint(point3);
const rect = { x:33, y;: 3, width: 30, height: 80};
printPoint(rect);
const color = { hex: "#187ABF"};
printPoint(color);
// @errors: 2345
interface Point {
x: number;
y: number;
}
function printPoint(p: Point) {
console.log(`${p.x}, ${p.y}`)
}
class VirtualPoint {
x: number;
y: number;
constructor(x: number, y: number){
this.x = x;
this.y = y;
}
}
const newVPOint = new VirtualPoint(13, 56);
printPoint(newVPoint); // "13, 56"