TIL [Typescript] Nomad 강의내용정리(6강~12강)

haileyself·2019년 10월 4일
0

Interface는 typescript에서 쓰이는 개념이지만, js에서는 해당 내용을 컴파일 하지 않는다.

Interface와 비슷한 기능을 하지만, js에서도 컴파일 되는 것은 바로 Class!

: Interface 가 typescript 측면에서는 더 안전하다, 하지만 리액트나 node, express와 같은 것을 사용할 때는 interface가 아닌 class를 사용하게 될 것

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;
    } 
} 

js에서의 클래스 형식과 비슷하지만, public 혹은 private을 정해줘야함!
js에서 클래스를 통해 객체를 만드는 것과 같이 constructor를 사용해서 각 인자들을 넣어줘야 한다.

  • public : class 안,밖으로 지정해놓은 값을 사용할 수 있음
  • private : class 안에서만 사용할 수 있음
    변수를 보호하고자 하거나, 클래스함수 밖에서 해당 인자가 호출되지않기를 원한다면 privated으로 설정하면 됨 !
    private으로 부른 값을 밖에서 사용하려고 하면 에러메시지가 뜸
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 hailey = new Human("Hailey", 29, "female");

console.log(hailey);

const sayHi = (person: Human): string  => {
    return `Hello ${person.name}, you are ${person.age}, 
	you are a ${person.gender}!
`;
};

console.log(sayHi(hailey));
 export {};

Human class의 age type을 private으로 설정하면,

이러한 에러메시지가 뜨면서 함수가 실행되지 않는다.

<참고 class>
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes

Static method

: method가 class안에 정의되었음에도 불구하고 class가 생성되지않았어도 사용할 수 있는 method !

class Block {
   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";

  
   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;
 }
}

Block.calculateBlockHash(); 

export {};

Block클래스를 생성하지 않았어도 Block의 static method인 calculateBlockHash 를 사용가능하다!

  • typescript를 통해서 함수의 결과 값도 미리 정해주고, 해당 타입이 아닐 때는 새로운 배열에 push되지않게도 만들 수 있음 !

  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 {};	

데이터타입을 만족하면, 새로운 block들이 계속 추가된다.

profile
Keep on my way ! :)

0개의 댓글