본문 바로가기

Frontend/TypeScript

Generic

반응형

TypeScript is a strongly type language and it significantly reduces the type errors while in development which would not be possible with mare JS. At the same time it also reduces the reusability of codes. If you want both the feature, The generic is a way to go. Without further ado, let's see how we can use the Generic

 

Without Type Checking

Below is an example of JavaScript code. JavaScript is a weakly typed language so when we define an array we can put any type of values.

// genetic.ts

class storage {
  private data:any[] = [];

  addData(newData) {
    this.data.push(newData)
  }
}

const data = new storage();
data.addData('new')
data.addData(1)

With Type Checking

It actually makes writing code easier but in some cases, it is possible that we only want the values with the same type. In that case this will lead to an error. Having a type checking helps us to prevent such a possible logical error.

On the other hand, type checking limits the flexibility of JavaScript as we can only use one specified type.

Genetic

Genetic is a way of providing the type as a parameter using angled brackets. 

// generic.ts

class storage<T> {
  private data: T[] = []

  addData(newData: T) {
    this.data.push(newData)
  }
}

const dataString = new storage<string>()
dataString.addData('ne')
dataString.addData('test')

const dataNumber = new storage<number>()
dataNumber.addData(1)
dataNumber.addData(2)

In this writing, we have seen how to use Genetic in TypeScript.

Source Code

https://github.com/jin-co/web-mobile/tree/master/TypeScript

 

GitHub - jin-co/web-mobile

Contribute to jin-co/web-mobile development by creating an account on GitHub.

github.com

 

728x90
반응형

'Frontend > TypeScript' 카테고리의 다른 글

Decorator  (3) 2023.05.12
Interface  (0) 2023.03.06
TypeScript  (0) 2023.03.06