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;
};
Top comments (0)