TypeScript utility Refine<T, P>

sylvaindethier

Sylvain Dethier

Posted on April 19, 2024

TypeScript utility Refine<T, P>

TL;DR

See my Refine Gist.

export type Refine<T, P extends Partial<T>> = {
  [k in keyof T]: T[k] & P[k];
};
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

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}`;
}>;
Enter fullscreen mode Exit fullscreen mode

The resulting RefinedType is:

type RefinedType = {
  aProp: `${number}`;
  someOtherProp: unknown;
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
sylvaindethier
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.

Related

TypeScript utility Refine<T, P>
typescript TypeScript utility Refine<T, P>

April 19, 2024