카테고리 없음

제네릭 <Type>

kim help 2022. 6. 9. 16:33
68 제네릭 <Type>

제네릭

  1. 제네릭스는 다양한 타입의 객체들을 다루는 메소드나 컬렉션 클래스에 컴파일 시 타입체크를 해주는 기능
  2. 객체의 타입은 컴파일 시에 체크하기 때문에 객체의 타입 안정성을 높이고 형변환의 번거로움이 줄어든다
  3. 타입 안정성을 높인다는 것은 의도하지 않는 타입의 객체가 저장되는 것을 막고, 저장된 객체를 꺼내올 때 원래의 타입과 다른 타입으로 잘못 형변환되어 발생할 수 있는 오류를 줄어준다는 것이다.

generic.ts

//원래는 interface안에 데이터 형식을 정해줘야 하는데

//class 안에서 지정을 해주면 사용 가능하다.

  

export  class  Output {

[address: string]: number

  

constructor(_address: string, _amount: number) {

this[_address] = _amount

}

}

  

export  class  Input {

public  signature: string  // 772210

  

constructor(_output: Output) {

this.signature = Input.sum(_output)

}

// const a:string

// function ab():string { }

static  sum(_output: Output): string {

const  value: string = Object.values(_output).join('')

return  value

}

}

generic.test.ts

const { describe, it } = require('@jest/globals')

import { SHA256 } from  'crypto-js'

import { Output, Input } from  './generic'

  

describe('Class Output 검증', () => {

let  output: Output

let  input: Input

  

it('Output 인스턴스 생성 확인', () => {

output = new  Output('7722', 10)

console.log(output)

})

  

it('Input 인스턴스 생성 확인', () => {

input = new  Input(output)

console.log(input)

})

  

it('txToString() 구현', () => {

//txToString(data):string

function  txToString<T>(_data: T) {

const  result = Object.entries(_data)

const  a = result.map((v) => {

return  v.join('')

})

return  a.join('')

}

  

const  inputResult = txToString<Input>(input)

console.log(inputResult)

  

const  outputResult = txToString<Output>(output)

console.log(outputResult)

  

SHA256(inputResult + outputResult).toString()

})

})