금일 달성 항목
1) 타입스크립트로 블록체인 만들기 완강
2) js 보충 특강 완강
3) 프로그래머스 0Lv 공부
문제 해결 과정 1 - typescript
[문제]
index.ts에 import를 하면 모듈을 가져오지 못하는 에러가 계속 떠서 진행할 수 없었습니다.
TypeScript ES6 import module File is not a module error
"crypto"에 자꾸만 빨간줄이 뜨며 에러가 뜹니다.
import * as 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.addBlock("Fourth one");
blockchain.getBlocks().push(new Block("xxxx", 1111, "Heeek")); // 누군가 임의로 해킹 할 수 있지만
console.log(blockchain.getBlocks());
[시도 및 해결]
tscomfig.json에 타입 경로를 추가해서 경로를 설정하는 방법도 있지만
"typeRoots": ["types/myPackage.d.ts"]
아래와 같이 npm i -D @type/node를 통해 타입스크립트에서 노드를 사용할 수 있도록 환경을 구축하면 손쉽게 오류가 해결이된다.
npm i -D @types/node
https://github.com/DefinitelyTyped/DefinitelyTyped
[알게된 점]
개인이 아닌 다양한 개발자들이 깃허브에 모아 만든 시스템이라는데 이런 다양한 소스들을 사용하면 코드 작성 시 더 유용할 것 같다.
'혼자 고민해보기_ 개발 > TIL (Today I Learned)' 카테고리의 다른 글
20230717(월)_ 백오피스 프로젝트 ERD 작성 (0) | 2023.07.19 |
---|---|
20230714(금)_ 프로그래머스 공부, 뉴스피드 프로젝트 주석달기 (0) | 2023.07.14 |
20230712(수)_ typescript 공부 (0) | 2023.07.12 |
20230711(화)_ 노드 JS 심화 과제 보충 (0) | 2023.07.11 |
20230710(월)_ 노드 JS 심화 Lv5 과제 완료 (1) | 2023.07.10 |