Front-end/타입스크립트로 블록체인 만들기 12

[TS] simple blockchain

index.ts // Module '"crypto"' has no default export. import crypto from "crypto" // import * as crypto from "crypto" interface BlockShape { hash: string prevHash: string height: number data: string } class Block implements BlockShape { public hash: string constructor( // no readonly => 접근 및 수정 가능 public readonly prevHash: string, public readonly height: number, public readonly data: string ) { t..

[TS] tsconfig.json

1. typescript 설치 npm i -D typescript 2. package.json 초기화 npm init -y "scripts": { "build": "tsc" // "npx tsc" } 3. tsconfig.json 설정 에디터는 우리가 TS로 작업한다는 것을 알게 되고, 자동완성기능을 제공한다. 디렉터리에 tsconfig.json 파일이 있으면 해당 디렉터리가 TypeScript 프로젝트의 루트임을 나타냅니다. tsconfig.json 파일은 프로젝트를 컴파일하는 데 필요한 루트 파일과 컴파일러 옵션을 지정합니다. include : It tells TS where to look for code to compile ourDir : It tells TS where to put the outp..

[TS] Polymorphism + Generic Type + Interface

// Storage는 이미 JS내 존재하여 재선언이 됨 interface SStorage { [key:string]: T } class LocalStorage { // 초기화할 것이 없기 때문에 constructor 사용하지 않음 private storage: SStorage = {} set(key: string, value: T) { if (this.storage[key] === undefined) { this.storage[key] = value } } get(key: string): T { if (this.storage[key] !== undefined) { return this.storage[key] } } remove(key: string) { if (this.storage[key] === un..

[TS] Interfaces

interface의 두가지 용도 type vs. class 🏁 object type specific value of concrete type 오직 객체의 모양을 특정해주기 위함 type과 interface는 오브젝트의 모양을 결정한다는 공통점이 있지만, type은 다른 형태도 설명할 수 있는 반면 interface는 오직 객체만 가능하다. 그래서 type의 쓰임이 더 많다. 결론 object → interface 그 외 (type alias, 특정값 등) → type 이 방법이 더 객체지향 프로그래밍처럼 보여서 이해하기 쉽다 // interface로는 object 외 선언 불가 type Team = "red" | "blue" | "yellow" type Health = 1 | 5 | 10 type Pla..

[TS] Classes

객체지향 프로그래밍 - JS에는 없는 개념 1. 생성자 자동 생성 생성자의 파라미터를 써주기만 하면 consturctor() 함수 자동 생성 // TypeScript class Player { constructor ( private firstName: string, private lastName: string ) {} } // JavaScript class Player { cosntructor (firstName, lastName) { this.firstName = firstName } } 2. 추상 클래스 (abstract class) 오직 다른 클래스에서 상속받을 수만 있는 클래스 직접 인스턴스 생성(인스턴스화) 불가 추상 메소드 추상 클래스 안에서 구현(implemetation)하지 않고 call ..

[TS] HW - Polymorphism, Generic Type

Question Second Answer // 배열의 마지막 요소 반환 type lastItem = (arr: T[]) => T const last: lastItem = (arr) => arr[arr.length-1] console.log('last item', last([1, 2, 3])) // 배열 시작부에 item 삽입 및 반환 type fullArr = (arr: T[], item: T) => T[] const prepend: fullArr = (arr, item) => [item].concat(arr) console.log('prepend item', prepend([1, 2, 3], 0)) // 두 개의 배열을 섞어서 하나의 배열로 반환 type mixedArr = (arr1: T[], arr..

[TS] Polymorphism 다형성

in 그리스 poly : many, several, much, multi morpho- : form(형태), structure(구조), 모양 poly + morphos = many different structures.shapes.forms before 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, 4]) superPrint([true, false, true]) su..

[TS] Why not JavaScript

∵ Type Safety (타입 안정성) → 확실한 버그 감소 1. 잘못된 코드 작성 불가 이 코드를 실행하면 런타임 에러가 발생할 것이라고 경고 2. 함수 파라미터 개수 검사 JS는 지나치게 유연해서 에러를 잘 보여주지 않음 // ex1 [1, 2, 3, 4] + false // '1,2,3,4false' // ex2 function divide(a, b) { return a / b } divide("xxxxxx") // NaN // ex 3 const a = { a: 'A' } a.hello() // 실행 후 에러 발생 그 중 최악은 런타임 에러 좋은 프로그래밍 언어는 잘못된 코드면 실행조차 안되고 컴파일 실패 코드가 실행되기 전 에러 경고 알림

[TS] Overloading

Function/Method Overloading 하나의 함수가 서로 다른 여러 개의 call signature를 가졌을 때 발생한다. 1. 같은 기능을 하는 메소드를 하나의 이름으로 사용할 수 있다. 2. 메소드의 이름을 절약할 수 있다. 직접 작성하기보다 외부 패키지/라이브러리에서 빈번하게 발견될 수 있다 패키지나 라이브러리는 아래와 같이 두 가지 경우의 overloading으로 디자인돼있을 것이다 Case1. 매개변수 타입이 다른 경우 ex. in Next.js // object Router.push({ path: "/home", state: 1 }) // string Router.push("/home") type Config = { path: string, state: number } type P..