yarn init (그 후 엔터 쭉쭉) yarn global add typescript
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "ES2021",
"sourceMap": true
},
"include": ["index.ts"],
"exclude": ["node_modules"]
}
컴파일 옵션을 주는 것이다.
index.ts
console.log("hello");
tsc
tsc 명령어는 ts 파일을 컴파일해서 index.js랑 index.js.map을 만든다.
node indes.js
컴파일된 파일 실행
원래는 yarn start 명령어만 입력하면 알아서 컴파일하고 실행되게 설정을 해놨지만 안돼서 일단 설정은 놔두고, 수동으로 컴파일하고 실행해준다.
{ "name": "nomad-typescript", "version": "1.0.0", "main": "index.js", "license": "MIT", "scripts": { "start": "node index.js", "prestart": "tsc" } }
VSCode에서 TSLint를 설치하면 타입이 안맞을 경우 바로 알려준다.
npm i -D @types/node typescript ts-node
혹시 에러가 날 경우 상단 명령어 실행
yarn start
를 입력하면 컴파일과 실행이 이제 한번에 된다.
index.ts
interface Human {
name: string;
age: number;
gender: string;
}
const person = {
name: "nicolas",
age: 2,
gender: "male",
}
const sayHi = (person: Human): string => {
return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`;
}
console.log(sayHi(person));
export {};
하지만 js 컴파일된 것을 보면 인터페이스가 없다. js에도 쓰고 싶다면 클래스를 쓰자.
index.ts
class Human {
public name: string;
public age: number;
public gender: string;
constructor(name: string, age: number, gender: string) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
const lynn = new Human("Lynn", 18, "female");
const sayHi = (person: Human): string => {
return `Hello ${person.name}, you are ${person.age}, you are a ${person.gender}`;
}
console.log(sayHi(lynn));
export {};
index.ts
import { timeStamp } from "console";
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, "202020202", "", "hello", 123456);
let blockChain: [Block] = [genesisBlock];
console.log(blockChain);
export {};
blockChain은 블록들을 담고 있는 체인이다. 여기서는 배열로 나타냈다.
yarn add crtpyo-js
index.ts
import * as CryptoJS from "crypto-js"
class Block {
public index: number;
public hash: string;
public previousHash: string;
public data: string;
public timestamp: number;
static calculateBlockHash = (index:number, previousHash: string, timestamp: number, data: string): string =>
CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
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, "202020202", "", "hello", 123456);
let blockchain: [Block] = [genesisBlock];
const getBlockchain = (): Block[] => blockchain;
const getLatestBlock = () : Block => blockchain[blockchain.length - 1];
const getNewTimeStamp = ():number => Math.round(new Date().getTime() / 1000);
console.log(blockchain);
export {};
const getNewTimeStamp = ():number => Math.round(new Date().getTime() / 1000);
위 코드는 number를 반환하는 숫자를 정의한 것이다.
index.ts
import * as CryptoJS from "crypto-js"
import { abort } from "process";
class Block {
public index: number;
public hash: string;
public previousHash: string;
public data: string;
public timestamp: number;
static calculateBlockHash = (index:number, previousHash: string, timestamp: number, data: string): string =>
CryptoJS.SHA256(index + previousHash + timestamp + data).toString();
static validateStructure = (aBlock: Block): boolean =>
typeof aBlock.index === "number" &&
typeof aBlock.hash === "string" &&
typeof aBlock.previousHash === "string" &&
typeof aBlock.timestamp === "number" &&
typeof aBlock.data === "string";
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, "202020202", "", "hello", 123456);
let blockchain: [Block] = [genesisBlock];
const getBlockchain = (): Block[] => blockchain;
const getLatestBlock = () : Block => blockchain[blockchain.length - 1];
const getNewTimeStamp = ():number => Math.round(new Date().getTime() / 1000);
const createNewBlock = (data:string) : Block => {
const previousBlock: Block = getLatestBlock();
const newIndex: number = previousBlock.index + 1;
const newTimeStamp: number = getNewTimeStamp();
const newHash: string = Block.calculateBlockHash(newIndex, previousBlock.hash, newTimeStamp, data);
const newBlock: Block = new Block(newIndex, newHash, previousBlock.hash, data, newTimeStamp);
addBlock(newBlock);
return newBlock;
}
const getHashforBlock = (aBlock: Block):String => Block.calculateBlockHash(aBlock.index, aBlock.previousHash, aBlock.timestamp, aBlock.data);
const isBlockValid = (candidateBlock: Block, previousBlock: Block): boolean => {
if (!Block.validateStructure(candidateBlock)) {
return false;
} else if (previousBlock.index + 1 !== candidateBlock.index) {
return false;
} else if (previousBlock.hash !== candidateBlock.previousHash) {
return false;
} else if (getHashforBlock(candidateBlock) !== candidateBlock.hash) {
return false;
} else {
return true;
}
};
const addBlock = (candidateBlock: Block) : void => {
if (isBlockValid(candidateBlock, getLatestBlock())) {
blockchain.push(candidateBlock);
}
};
createNewBlock("second block");
createNewBlock("third block");
createNewBlock("fourth block");
console.log(blockchain);
export {};