혼자 고민해보기_ 개발/TIL (Today I Learned)

20230713(목)_ typescript 공부, js 보충특강 수강

nuri-story 2023. 7. 13. 22:29

금일 달성 항목

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

 

[알게된 점]

개인이 아닌 다양한 개발자들이 깃허브에 모아 만든 시스템이라는데 이런 다양한 소스들을 사용하면 코드 작성 시 더 유용할 것 같다.