View

TIL | TypeScript_기본문법2

Melody:) 2021. 10. 10. 07:44

Interface 만들기

typscript

interface Human {
    name  : string;
    age   : number;
    gender: string;
}

const person = {
    name  : "Melody",
    age   : 29,
    gender: "Female"
}


const sayHi = (person : Human):string => { 
    return `hi, I'm ${person.name}, ${person.gender}, ${person.age}`;
};

console.log(sayHi(person));

export {};

typscript -> javastript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const person = {
    name: "Melody",
    age: 29,
    gender: "Female"
};
const sayHi = (person) => {
    return `hi, I'm ${person.name}, ${person.gender}, ${person.age}`;
};
console.log(sayHi(person));
//# sourceMappingURL=index.js.map

Class

interface는 타입스크립트에서만 작동한다.

간혹 interface를 자바스크립트에 넣어주고 싶을 때가 있는데, 이때는 Class를 사용하면 된다.

자바스크립트에서는 클래스의 속성(property)들을 묘사할 필요가 없다.

타입스크립트에서는 클래스가 어떤 속성(private, public)을 가지고

그 속성들의 권한(permission)를 설정해주어야 한다.

예를 들어 name이라는 변수에 public 속성을 선언해주고, Type을 설정해줄수있다.

생성자 : 생성자는 클래스가 호출될때 마다 실행된다.

typscript

class Human {
    public name   : string;
    public age    : number;
    public gender : string;
    constructor (name:string, age:number, gender:string) {
// 클래스의 name, age, gender가 이 생성자의 name, age, gender와 같다는 뜻.
        this.name   = name;
        this.age    = age;
        this.gender = gender;
    } 
}

const Melody = new Human("Melody", 24, "Female");

const sayHi = (person : Human):string => { 
    return `hi, I'm ${person.name}, ${person.gender}, ${person.age}`;
};

console.log(sayHi(Melody));

export {};

typscript -> javastript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Human {
    constructor(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

const Melody = new Human("Melody", 24, "Female");
const sayHi = (person) => {
    return `hi, I'm ${person.name}, ${person.gender}, ${person.age}`;
};
console.log(sayHi(Melody));
//# sourceMappingURL=index.js.map

위 처럼 js파일에도 class가 생기는 것을 볼수 있다.
상황에 따라서 interface가 필요하고 class가 필요하지 않을 때가 있다.
이는 js코드가 인터페이스를 사용하게되면, ts측면에서 좀더 안정하기 때문이다.

private, public

히지만 만약, react를 쓰거나, node, express를 사용하면, 코드에서 클래스를 사용해야한다.
ts의 public 변수는 js에서 나타나지 않는다. 그이유는 js는 public과 privae의 개념이 없기 때문이다.
ts에서 클래스 내부에 private 변수가 있다면, 이것은 class 내부에서면 접근가능하다.
따라서 class 밖에서 호출하고 있다면, 이것을 js로 컴파일 하지 않을 것이다.

이것은 ts의 강력한 기능이며, 클래스 외부에서 해당 privae한 변수의 값이 호출, 변경 되는 것을 방지하고, 보호할 수 있다.

typscript

class Human {
    public name   : string;
    private age    : number;
    public gender : string;
    constructor (name:string, age:number, gender:string) {
        this.name   = name;
        this.age    = age;
        this.gender = gender;
    } 
}
const Melody = new Human("Melody", 24, "Female");

const sayHi = (person : Human):string => { 
    return `hi, I'm ${person.name}, ${person.gender}, ${person.age}`;
};

console.log(sayHi(Melody));
export {};
//콘솔
//오후 6:15:57 - File change detected. Starting incremental compilation...
//src/index.ts(16,64): error TS2341: Property 'age' is private and only accessible within class 'Human'.
//오후 6:15:57 - Found 1 error. Watching for file changes.

typscript -> javastript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Human {
    constructor(name, age, gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}
const Melody = new Human("Melody", 24, "Female");
const sayHi = (person) => {
    return `hi, I'm ${person.name}, ${person.gender}, ${person.age}`;
};
console.log(sayHi(Melody));
//# sourceMappingURL=index.js.map

Block chain 만들기

class Block {
    public index        : number;
    public hash         : string;
    public priviousHash : string;
    public data         : string;
    public timestamp    : number;
    constructor(
        index        : number,
        hash         : string,
        priviousHash : string,
        data         : string,
        timestamp    : number
    ) {
        this.index        = index;
        this.hash         = hash;
        this.priviousHash = priviousHash
        this.data         = data;
        this.timestamp    = timestamp;
    }
}

const genesisBlock : Block = new Block(1, "12315646512", "", "Meody", 20211009);

let blockchain: Block[] = [genesisBlock]

console.log(blockchain)

export{};

1. genesisBlock : Block의 타입을 갖는 값들을 가진 객체를 생성해 줌.

2. blockchain : [Block] : 변수 blockchain의 타입은 리스트이며, 리스트 안의 값은 Block과 같은 타입이 만 들어올 수 있다.


crypto 설치

npm

npm install crypto-js
npm i --save-dev @types/crypto-js

또는

yarn

yarn add crypto-js

import

npm

var CryptoJS = require("crypto-js");

또는

yarn

import * as CryptoJS from "crypto-js";

Static

static method 란?

method가 Block 클래스 안에 있고, 해당 클래스가 앞에서 생성되지 않았어도, 호출할 수 있는 메소드라는 뜻.

import * as CryptoJS from "crypto-js";

class Block {
    public index        : number;
    public hash         : string;
    public priviousHash : 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,
        priviousHash : string,
        data         : string,
        timestamp    : number
    ) {
        this.index        = index;
        this.hash         = hash;
        this.priviousHash = priviousHash
        this.data         = data;
        this.timestamp    = timestamp;
    }
}

//const genesisBlock : Block = new Block(1, "12315646512", "", "Meody", 20211009);
//앞에서 Block이 생성되지 않아도됨.

Block.calculateBlockHash(0,"",0,"");

Block chain 기능(Method) 만들기

1. 블록체인 배열 가져오기

const getBlockchain = ():Block[] => blockchain;

2. 최신 블록 가져오기

const getLatesBlock = ():Block => blockchain[blockchain.length -1];

3. 현재 날짜와 시간 생성하기

const getNewTimeStamp =():number => Math.round(new Date().getTime() / 1000);
class Block {
    public index        : number;
    public hash         : string;
    public priviousHash : 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,
        priviousHash : string,
        data         : string,
        timestamp    : number
    ) {
        this.index        = index;
        this.hash         = hash;
        this.priviousHash = priviousHash
        this.data         = data;
        this.timestamp    = timestamp;
    }
}

const getBlockchain = ():Block[] => blockchain;

const getLatesBlock = ():Block => blockchain[blockchain.length -1];

const getNewTimeStamp =():number => Math.round(new Date().getTime() / 1000);

Block validate 메서드 만들기

1. Block 클래스에 안에 validateBlock 매소드 추가(타입 검증)

class Block {

    static validateBlock = (ablock:Block):boolean => 
        typeof ablock.index        === "number" &&
        typeof ablock.hash         === "string" &&
        typeof ablock.priviousHash === "string" &&
        typeof ablock.data         === "number" &&
        typeof ablock.timestamp    === "number" 

2. isValidateBlock 함수 생성 : 신생 블락의 타입, 이전 블락의 Hash, 신생블락의 Hash 검증

const isValidateBlock = (candidateBlock: Block, previousBlock: Block): boolean => {
    if (!Block.validateBlock(candidateBlock)){
        return false;
    } else if (previousBlock.index + 1 !== candidateBlock.index) {
        return false;
    } else if (previousBlock.hash !== candidateBlock.priviousHash) {
        return false;
    } else if (getHashforBlock(candidateBlock) !== candidateBlock.hash) {
        return false;
    } else {
        return true;
    };
};

3. addBlock 함수 생성 : 신생 블락을 blockchain 리스트에 추가

const addBlock = (cadidateBlock:Block):void => {
    if (isValidateBlock(cadidateBlock, getLatesBlock())) {
        blockchain.push(cadidateBlock);
    };
};

4. createNewBlock : 새로운 블락을 생성하고 blockchain 리스트에 추가

const createNewBlock = (data: string):Block => {
    const previousBlock:Block  = getLatesBlock();
    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;
}    

콘솔에 찍힌 결과


createNewBlock("Melody1");
createNewBlock("Melody2");
createNewBlock("Melody3");
createNewBlock("Melody4");


----------------

오후 5:46:28 - Found 0 errors. Watching for file changes.
[
  Block {
    index: 0,
    hash: '12315646512',
    priviousHash: '',
    data: 'Meody',
    timestamp: 20211009
  },
  Block {
    index: 1,
    hash: 'dee2466d36faee97da946058a05cc984b2f2ded97f64d1c494d31a368c5e600f',
    priviousHash: '12315646512',
    data: 'Melody1',
    timestamp: 1633855589
  },
  Block {
    index: 2,
    hash: '8ebf07925ccbfa327cbeb299f15b526967eb71f755cdbb02fa77e1083c9d06fa',
    priviousHash: 'dee2466d36faee97da946058a05cc984b2f2ded97f64d1c494d31a368c5e600f',
    data: 'Melody2',
    timestamp: 1633855589
  },
  Block {
    index: 3,
    hash: 'd0084e2b970439fdb2381a66f6e7add0a49486b13412ce67af90e367ce6905e8',
    priviousHash: '8ebf07925ccbfa327cbeb299f15b526967eb71f755cdbb02fa77e1083c9d06fa',
    data: 'Melody3',
    timestamp: 1633855589
  },
  Block {
    index: 4,
    hash: '022f77abf70c38def455909be0ee83bbb2f2ff0443e669ac017196859dc36f31',
    priviousHash: 'd0084e2b970439fdb2381a66f6e7add0a49486b13412ce67af90e367ce6905e8',
    data: 'Melody4',
    timestamp: 1633855589
  }
]

'NestJS' 카테고리의 다른 글

TIL | NestJS_REST_API_Controller  (0) 2021.10.11
TIL | NestJS_REST_API_Settings  (0) 2021.10.11
TIL | TypeScript_기본 문법1  (0) 2021.10.10
TIL | Typescript_Setting_초기개발환경세팅  (0) 2021.10.07
TIL | Node_개발환경세팅  (0) 2021.10.05
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31