본문 바로가기

개발에 도움이 되는/TypeScript

(6)
TypeScript 기본 (Utility Type) 1. keyof interface의 key 값을 union 형태로 받을 수 있음 - 예제 interface User { id: number; name: string; age: number; gender: "M" | "F"; } type UserKey = keyof User; const uk:UserKey = "age" // User interface에 있는 key 값만 가능 2. Partial property를 optional 하게 만들어 줌 - 예제 interface User { id: number; name: string; age: number; gender: "M" | "F"; } let admin: Partial = { id: 1, name: "An", }; // Partial을 사용하면 User..
TypeScript 기본 (Generic) - Generic class, function, interface를 다양한 type으로 재사용 가능 변수 type의 변수 다른 인자가 들어가도 상관없지만 보통 T를 사용 - 기본 예제 1. function function getSize(arr: T[]): number { return arr.length; } const numArr = [1, 2, 3]; getSize(numArr); // 3 const strArr = ['A', 'B', 'C', 'D']; getSize(strArr); // 4 // generic으로 선언하면 굳이 타입 지정해주지 않아도 알아서 판단하긴 함 const boolArr = [false, true, false]; getSize(boolArr); // 3 2. interface..
TypeScript 기본 (Literal, Union / Intersection Type) - Literal Type string, number, boolean 같은 type을 이용하여 정확한 값을 지정 가능 - 기본 예제 type Job = "developer" | "teacher" | "singer"; interface User { name : string; job : Job; } const An: User = { name : "An", job : "developer"; // Job에 선언된 것 외에 다른 것으로 선언하면 에러 } - Union Type 여러 type이 올 수 있는 경우에 사용하면 좋음 (or의 의미) - 기본 예제 interface Food { name : "food"; type : string; eat() : void; } interface Drink { name : "..
TypeScript 기본 (Function) - Function 매개변수 및 return 값에 대한 type을 지정 - 기본 function 함수명(매개변수: type): return type { // 아무것도 return 하지 않으면 void } // arrow function const 함수명 = (매개변수: type) : return type => { } ex) function add(num1: number, num2: number) : number{ return num1 + num2; } - 선택적 매개 변수 (Optional) ex) function sayHello(name?: string): string { return `Hello, ${name || "world"}`; } const result = hello(); const resul..
TypeScript 기본 (Type, Interface) - Type number ex) let age:number = 31; string ex) let name:string = "An"; boolean ex) let isMan:boolean = true; Array / type[] : type에는 적용할 type 입력 ex) let score:number[] = [100, 90, 80]; ex) let score:Array = [100, 90, 80]; [type, type] : Tuple로 사용, type에는 적용할 type 입력 ex) let an:[string, number]; an = ["an", 31]; // 해당 type 순서가 일치해야하며, 해당 type에 있는 메서드만 사용 가능 void : 반환하지 않는 함수에 사용 ex) function d..
TypeScript 개념 및 설치 방법 (React) - TypeScript JavaScript의 SuperSet(상위 확장)인 오픈소스 프로그래밍 언어이다. 동적 타입인 JavaScript는 소규모일 땐 편할지 몰라도 대규모 혹은 다른 사람과 협업을 해야 되는 상황에서는 동적 타입은 직관적으로 어떤 타입의 변수인지 알 수 없어 치명적이다. TypeScript는 JavaScript에 Type 문법을 더하여 이러한 문제를 해소하고자 나왔다. 또한 에러 메시지 수준도 올라갔다. - 기본 설치 (기본 html + css + typescript 개발 시) 1) typescript 설치 (global) npm install -g typescript 2) tsconfig.json 생성 후 아래 내용 작성 { "compilerOptions": { "target": "e..

반응형