DEV Community

Cover image for TypeScript utility Refine<T, P>
Sylvain Dethier
Sylvain Dethier

Posted on

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

Top comments (0)