아래의 영상을 보고 개인적으로 정리한 글입니다
링크 : 노마드 코더의 타입스크립트 강의
간단한 blockchain
을 만들어 보았다.
// src/index.ts
class Block {
public index: number;
public hash: string;
public previousHash: string;
public data: string;
public timestamp: number;
constructor(
index: number,
hash: string,
previousHash: string,
data: string,
timestamp: number,
) {
this.index = index;
this.hash = hash;
this.previousHash = previousHash;
this.data = data;
this.timestamp = timestamp;
}
}
const genesisBlock: Block = new Block(0, "2020202020", "", "Hello", 123456);
let blockchain: Block[] = [genesisBlock]; // blockchain 은 type이 Block 인 값만 저장함. 즉, type 이 Block이 아니면 어떠한 값도 넣을 수 없음
blockchain.push('BlockChain');
blockchain.push(123123);
blockchain.push(new Block(1, "20212021", "", "Block2", 44));
console.log(blockchain)
코드를 위와 같이 작성하면 blockchain.push('BlockChain');
그리고 blockchain.push(123123);
에서 어레가 발생할 것이다.
let blockchain: [Block]
에서 blockchain
의 type
을 block
으로 지정해주었기 때문이다. 반면에 blockchain.push(new Block(1, "20212021", "", "Block2", 44));
에러가 나지 않고 blockchain
에 push
되는 것을 볼 수 있다.
static
으로 calculateBlockHash
함수를 추가해준다.
// src/index.ts
class Block {
public index: number;
...
...
static calculateBlockHash = (
index: number,
previousHash: string,
timestamp: number,
data: string
): string => CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
constructor(
...
...
)
static
을 사용하는 부분에서 JAVA
와 굉장히 비슷하다고 느꼈는데
먼저 static
을 사용하지 않으면 Block
타입으로 생성된 객체
에서만 calculateBlockHash
함수를 호출 할 수 있지만 static
을 붙여줌으로써 객체
생성 없이 다음과 같이 호출 가능하다. Block.calculateBlockHash(0, "1", 33, "2020")
Static
이 없다면 Block
에서 calculateBlockHash
속성을 찾을 수 없다. 즉, new Block(1, "20212021", "", "Block2", 44).calculateBlockHash(0, "1", 33, "2020")
과 같이 작성해야 호출 할 수 있다.