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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay