Typescript: How to use Generics to make your own Type Templates?
Taric Ov
Posted on June 1, 2023
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 }>;
}
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];
};
Here we go.. This is a type template of a readonly
that converts any type props into readonly mode using the keyword readonly
:
We use
<T>
as our parameter of props.And then we use this syntax
[P in keyof T]
to loop through props keys and re-print them w/ the prepended keywordreadonly
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
As you see how generics:
makes things handy
generates from already existing types,
prevents us from repeating/re-typing props (reusability)
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.
Posted on June 1, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.