Definitely Types
Definitely Typed는 타입스크립트의 가장 큰 장점 중 하나입니다. 커뮤니티는 효과적으로 자바스크립트 프로젝트의 거의 90%가 자연스럽게 진행되고 문서화되었습니다.
@types 사용
npm을 이용해서 꽤 간단하게 설치가 가능합니다. 예를 들어 jquery에 대한 타입 정의를 다음과 같이 간단히 할 수 있습니다.
npm i @types/jquery --save-dev
@types는 전역과 모듈 타입 정의를 모두 지원합니다.
< 전역 @types >
기본적으로 전역 소비를 지원하는 모든 정의가 자동으로 포함됩니다. 예: jquery의 경우 프로젝트 전역에서 $를 사용할 수 있어야 합니다.
그러나 jquery와 같은 라이브러리의 경우 일반적으로 모듈로 사용하는 걸 추천합니다.
< 모듈 @types >
설치 후 특별한 구성이 필요하지 않습니다. 모듈처럼 다음과 같이 사용하면 됩니다.
import * as $ from 'jquery'
Block
import crypto from "crypto"; interface BlockShape { hash: string; prevHash: string; height: number; data: string; } class Block implements BlockShape { public hash: string; constructor( public prevHash: string, public height: number, public data: string ) { this.hash = Block.calculateHash(prevHash, height, data); } static calculateHash( prevHash: string, height: number, data: string ) { const toHash = `${prevHash}${height}${data}`; return crypto .createHash("sha256") .update(toHash) .digest("hex"); } } class Blockchain { private blocks: Block[]; constructor() { this.blocks = []; } private getPrevHash() { if (this.blocks.length === 0) return ""; return this.blocks[this.blocks.length - 1].hash; } public addBlock(data: string) { const newBlock = new Block( this.getPrevHash(), this.blocks.length + 1, data ); this.blocks.push(newBlock); } public getBlocks() { return [...this.blocks]; } } const blockchain = new Blockchain(); blockchain.addBlock("First one"); blockchain.addBlock("Second one"); blockchain.addBlock("Third one"); blockchain .getBlocks() .push(new Block("xxxxx", 11111, "HACKEDD")); console.log(blockchain.getBlocks());
다음과 같이 코드를 작성하면 끝입니다.

'Web > TypeScript' 카테고리의 다른 글
Typescript Practice - Block Chain Project - Basic (0) | 2022.05.07 |
---|---|
TypeScript Practice - Class, Interface (0) | 2022.05.07 |
Typescript Practice - Functions (0) | 2022.05.07 |
Typescript Practice - OverView (0) | 2022.05.07 |