TypeScript utility Refine<T, P>
Sylvain Dethier
Posted on April 19, 2024
TL;DR
See my Refine
Gist.
export type Refine<T, P extends Partial<T>> = {
[k in keyof T]: T[k] & P[k];
};
Why ?
For a project I have the need to be able to (kind of) extend a type but keep it's original type. Let me explain.
Say you have a type
type TheType = {
aProp: string;
someOtherProp: unknown;
};
But you whish the aProp
to be a more specific type for example `${number}`
(which is still a string
type). The extends
keyword is not restrictive enough (IMO) because it lets you completly override the original type, for example with boolean
.
So I have to define a Refine<T,P>
utility type.
Example and usage
type TheType = {
aProp: string;
someOtherProp: unknown;
};
type RefinedType = Refine<TheType, {
aProp: `{$number}`;
}>;
The resulting RefinedType
is:
type RefinedType = {
aProp: `${number}`;
someOtherProp: unknown;
};
💖 💪 🙅 🚩
Sylvain Dethier
Posted on April 19, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.