Typescript: How to use Generics to make your own Type Templates?

taricov

Taric Ov

Posted on June 1, 2023

Typescript: How to use Generics to make your own Type Templates?

After we talked about types utilities the last post, let's extend and see more advanced usage of generics in typescript and we could build our own type templates that can be reused across your projects:

let's say that we will type a social tweet/post data…


interface postProps {
  name: string;
  relativeTime: string;
  tweet: string;
  retweets: number;
  likes: number;
  comments: number;
  userImg: string;
  liked: () => void;
  likedUsers: Array<{ name: string; img_src: string; id: number }>;
}

Enter fullscreen mode Exit fullscreen mode

we are familiar now w/ interfaces in typescript and to put it in simple quick words, interfaces are type contracts that an entity/object should conform to.

Now..


type readOnlyProps<T> = {
  readonly [P in keyof T]: T[P];
};

Enter fullscreen mode Exit fullscreen mode

Here we go.. This is a type template of a readonly that converts any type props into readonly mode using the keyword readonly:

  1. We use <T> as our parameter of props.

  2. And then we use this syntax [P in keyof T] to loop through props keys and re-print them w/ the prepended keyword readonly

  3. T[P] is so obviously bringing in the value of the key for each prop

Now we can use this template, like this:


type readOnlyPostPorps = readOnlyProps<postProps>;
//readOnlyPostPorps is our new type
//readOnlyProps is our type template/converter we defined b4
//postProps us our original interface

Enter fullscreen mode Exit fullscreen mode

As you see how generics:

  1. makes things handy

  2. generates from already existing types,

  3. prevents us from repeating/re-typing props (reusability)

  4. opens possibilities for more complex flows

Now..

Try out the example and play around w/ the template and see what you can come up w/ new:

till next time.. keep ur type tight.

💖 💪 🙅 🚩
taricov
Taric Ov

Posted on June 1, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related