본문 바로가기

TypeScript13

[타입스크립트] 타입스크립트 설정파일 설명 (tsconfig.json) tsconfig.json파일이 있으면 vs code는 프로젝트가 타입스크립트를 사용한다는 것을 알게 되고 타입스크립트 자동완성 기능을 제공해준다. tsconfig.json { "include": ["src"], "compilerOptions": { "outDir": "build", "target": "es5", "lib": ["ES6", "DOM"], "strict": true, "allowJs": true, // 타입스크립트 파일에 자바스크립트 import 가능하게 하기 "esModuleInterop": true, "module": "CommonJS" } } 1. include 타입스크립트 파일이 어디에 위치하는지 배열 안에는 자바스크립트로 컴파일하고 싶은 모든 디렉토리를 명시 타입스크립트가 src 폴.. 2022. 12. 7.
[타입스크립트] 빌드없이 타입스크립트 실행하기 & 서버 자동으로 재시작하기 package.json npm run build && npm run start 명령어로 빌드 후에 프로젝트를 실행 "scripts": { "build": "tsc", "start": "node build/index.js" // 빌드 후 index.js 실행하라는 명령어 } ts-node 빌드 없이 빠르게 새로고침하고 싶을때 사용한다. 빌드한 다음에 코드를 실행하지 않아도 ts-node가 컴파일할 필요없이 타입스크립트 코드를 대신 실행해준다. ts-node 개발용으로 설치 npm i -D ts-node package.json "scripts": { "build": "tsc", "dev": "ts-node src/index", // 추가된 코드 "start": "node build/index.js" } no.. 2022. 11. 29.
[타입스크립트] 다형성(polymorphism) 제네릭(generic) 클래스(class) 인터페이스(interface) 합치기 다형성: 다른 모양의 코드를 가질 수 있게 해주는 것 (제네릭 사용) 제네릭은 placeholder 타입을 쓸 수 있도록 해줌 (placeholder concrete) 타입스크립트가 placeholder 타입을 concrete 타입으로 바꾸어줌 예제 브라우저에서 쓰는 로컬스토리지 API와 비슷한 API 만들고 타입만 넣어주기 // Storage is reserved word interface SStorage { [key:string]: T } class LocalStorage { private storage: SStorage = {} set(key:string, value:T){ this.storage[key] = value } remove(key:string){ delete this.storage[ke.. 2022. 11. 20.
[타입스크립트] 인터페이스란? (인터페이스와 클래스의 차이점) 인터페이스란? 오브젝트의 타입을 설정하는 일종의 오브젝트 설계도 + 추상화 클래스와 같이 표준화된 프로퍼티와 메서드를 갖도록하는 설계도 추상화 클래스 vs 인터페이스 공통점: 클래스의 모양을 결정할 수 있다 (클래스의 프로퍼티와 메서드를 지정) 클래스: 추상화 클래스는 자바스크립트로 변환되며 추상화 클래스를 상속받은 클래스의 프로퍼티와 메소드에 private, protected, public를 지정할 수 있다 인터페이스: 인터페이스는 자바스크립트로 변환되지 않아 파일이 가벼워지며 인터페이스를 상속받은 클래스의 프로퍼티와 메소드에는 public만 지정할 수 있다 추상화 클래스 예제 클래스 Player에서는 User의 모든 메서드를 구현해야한다. abstract class User { constructor(.. 2022. 11. 17.
[타입스크립트] 인터페이스란? (인터페이스와 타입의 차이점) 인터페이스란? 오브젝트의 타입을 설정하는 일종의 오브젝트 설계도 타입 vs 인터페이스 공통점: 오브젝트의 모양을 결정할 수 있다 (오브젝트 타입지정 가능) 타입: 여러 데이터의 타입을 지정할 수 있다 인터페이스: 오직 오브젝트 데이터의 타입만을 지정할 수 있다 타입 예제 type Team = 'red' | 'blue' | 'yellow' type Health = 1 | 5 | 10 type Player = { nickname: string, team: Team, health: Health } const nico: Player = { nickname: 'nico', team: 'yellow', health: 10 } 인터페이스 예제 type Team = 'red' | 'blue' | 'yellow' typ.. 2022. 11. 15.
[타입스크립트] 타입의 종류와 인터페이스 타입의 종류 1. 오브젝트 모양 알려주기 type Player = { nickname: string, healthBar: number } 2. 특정 타입이라고 지정해주기 (concrete type) type Food = string const kimchi:Food = 'delicious' type Friends = Array const kakao:Friends = ['Ryan', 'Muzi', 'Apeach', 'Frodo'] 3. alias(대체명, 별명)를 사용해 타입 지정해주기 type Nickname = string type Health = number type Player = { nickname: Nickname, healthBar: Health } 4. 특정값을 지정 타입을 지정된 옵션으로만 .. 2022. 11. 15.
[타입스크립트] readonly(읽기전용) 예제 클래스 Word의 프로퍼티가 public이므로 kimchi.def이 수정이 가능하다 type Words = { [key:string]: string } class Dict { private words: Words constructor(){ this.words = {} } add(word:Word) { if(this.words[word.term] === undefined) { this.words[word.term] = word.def } } def(term:string) { return this.words[term] } delete(term:string) { delete this.words[term] } } class Word { constructor( public term: string, publi.. 2022. 11. 15.
[타입스크립트] 클래스 타입스크립트에서 클래스 만들기 타입스크립트 class Player { constructor( private firstName:string, private lastName:string, public nickName:string ){} } const nico = new Player('nico', 'las', '니꼬') 자바스크립트 "use strict"; class Player { constructor(firstName, lastName, nickname) { this.firstName = firstName; this.lastName = lastName; this.nickName = nickname; } } const nico = new Player('nico', 'las', '니꼬'); 타입스크립트에서 접.. 2022. 11. 14.
[타입스크립트] 다형성(polymorphism)과 제네릭(generic) 다형성(polymorphism)이란? polymorphism이란 poly(many) + morphos(form)의 합성어로 다수의 형태라는 의미다 다형성이 없다면? 아래의 예제처럼 사용할 모든 타입을 미리 정의해주어야한다 type SuperPrint = { (arr: number[]): void (arr: boolean[]): void (arr: string[]): void (arr: (number|boolean)[]): void } const superPrint: SuperPrint = (arr) => { arr.forEach(i => console.log(i)) } superPrint([1, 2, 3]) superPrint([true, false, true]) superPrint(['a', 'b', .. 2022. 11. 3.
[타입스크립트] 오버로딩(overloading)이란? 오버로딩(overloading)이란? function overloading 또는 method overloading이라고 한다 오버로딩은 함수가 여러개의 call signatures를 가지고 있을때 발생된다 대부분의 경우 직접 오버로딩 함수를 작성할 일은 없다. 일반적으로 라이브러리 또는 패키지에서 오버로딩 함수가 있어 사용하는 경우가 더 많다 call signature vs overloading call signature type Add = (a: number, b: number) => number overloading 함수가 여러개의 다른 call signatures를 가지고 있을때 발생된다 아래의 예제와 같이 사용하는 함수는 많이 없을테지만 오버로딩의 핵심을 보여준다 type Add = { (a: n.. 2022. 11. 3.
[타입스크립트] 호출 시그니처(call signature) 호출 시그니처(call signature)란? 함수가 선언되기 전에 타입을 미리 지정해 여러번 재사용할 수 있도록 하는 것을 call signature라고 한다 call signature는 함수를 어떻게 호출해야하는 것인지 알려준다 (일종의 타입 템플릿) call signature는 함수의 인자와 반환 타입을 알려준다 type Add = (a:number, b:number) => number // call signature const add: Add = (a, b) => a + b // 함수 add의 타입으로 call signature를 사용 2022. 10. 23.
[타입스크립트] 타입스크립트 기초문법 13가지 1. 원시형 데이터에 타입 지정 변수에 타입 지정하는 기본 문법 : 타입 let a : number = 1 let b : string = 'hello world' let c : boolean = true let d : undefined = undefined let e : null = null 원시형 데이터(number, string, boolean, undefined, null 등)를 변수에 할당할때는 타입을 지정하기 보다는 타입스크립트가 자동으로 타입을 추론하도록 두는 것이 낫다. 아래의 코드를 타입스크립트에서 사용하면 a, b, c가 어떤 데이터 타입을 사용해야하는지 타입스크립트는 이미 알고 있으므로 코드의 가독성을 위해 타입 지정을 하지 않는 편이 좋다. let a = 1 let b = 'hello.. 2022. 9. 16.
[타입스크립트] TypeSciprt 사용이유와 설치방법 TypeScript란? 자바스크립트에 타입을 더한 언어 TypeSciprt 탄생배경 자바스크립트는 Dynamic Typing을 지원하는 타입에 관대한 언어다 이로 인해서 문제점이 생기는데 코드가 길어지거나 프로젝트 규모가 커질때 에러가 발생할 확률이 높다 다른 사람이 짠 자바스크립트 코드를 수정할때 어려움이 있다 이러한 문제점을 보완하기 위해 자바스크립트 언어에 타입을 더한 타입스크립트 언어가 탄생하였다 설치방법 HTML CSS JS 1. 타입스크립트 설치 npm install -g typescript 2. 타입스크립트 파일생성 index.ts 3. 타입스크립트 자바스크립트로 변환 웹브라우저가 이해할 수 있는 자바스크립트로 컴파일해준다. 터미널에서 아래의 명령어를 입력하면 ts를 변환한 js 파일이 생성.. 2022. 9. 16.