DEV Community

Nily
Nily

Posted on

1

[Typescript] Study TS with me (2) - Generics

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.

Generics makes it easier to write reusable code.

제네릭은 JavaC++ 같은 정적 타입 언어에선 이미 널리 쓰이고 있는 기능이라고 한다. 다양한 타입에서 작동한다는 장점이 있기 때문에 component를 만들때 유용하게 쓰일 수 있다.

1. Function

function identity<T>(arg: T): T {
  return arg;
}

// 함수를 호출하는 순간 Type이 결정됨.
const output1 = identity(3); // number
const output2 = identity('myName'); // string
Enter fullscreen mode Exit fullscreen mode

2. Class

class SimpleImage<T, S> implements Image<T, S>{
  constructor(
    private _title: T,
    private _size: S,
  ){}

  title(): T {
    return this._title;
  }
  size(): S {
    return this._size;
  }
}

const simpleImage = new SimpleImage({ main: 'sample image'}, 300);
Enter fullscreen mode Exit fullscreen mode

3.1 Generic Constraints

interface Lengthwise {
  length: number;
}

function logginIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);

  return arg;
}

// 제네릭 함수의 타입이 제한되어 있기 때문에, 모든 타입에 대해선 동작하지 않음.
logginIdentity(3); // Error

// length property가 있는 type을 전달해야 함.
logginIdentity({ length: 10, value: 3 });

Enter fullscreen mode Exit fullscreen mode

3.2 Using Type Parameters in Generic Constraints

// obj에 존재하는 property만 가져오도록
function getProperty<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

const x = {
  a: 1, 
  b: 2, 
  c: 3,
  d: 4
}

getProperty(x, 'a');
getProperty(x, 'f'); // Error: f는 x에 존재하지 않는 property
Enter fullscreen mode Exit fullscreen mode

--

scss에서 많이 쓰이는 디자인 패턴인 mixins을 만드는데도 Generic이 쓰였다고 하니, 나중에 기회가 되면 또 포스팅 해봐야 겠다. (참고 링크)

[출처]

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more