I was trying to create new type from a type, but remove any property that it's value is undefined|null, this to create a fetch function that require/not require a payload argument.
The main type is:
type TEndpointsPayload = {
getList: undefined,
open: {
id: string
}
close: {
id: string
}
}
while I'm trying to create a new type that will look like so:
type TEndpointsNonEmptyPayload = {
open: {
id: string
}
close: {
id: string
}
}
So the getList is omitted because it's value is undefined/not an object.
I've tried many methods, include Omit, Exclude and so, but non seem to actully remove the property from the type, but instead set him as never..
Any help would be muhch appreciated!
The function looks something like so (assuming the TEndpointsNonEmptyPayload actually works):
private reuqest<T extends keyof TEndpointsNonEmptyPayload>(endpoint: T, payload: TEndpointsNonEmptyPayload[T]): void;
and to solve this I was thinking of creating some function overload looking like so:
private reuqest<T extends keyof TEndpointsPayload>(endpoint: T): void;
Would happy to hear some ideas on the type or the function implementation!
The implementation of OmitNullish<T> below excludes keys from being added to the mapped type at all if they have a value of type null|undefined, rather than setting their values to never. Does it do what you want?
Edit: It looks like me and Jcalz have arrived at not only the same answer, but even the same alias OmitNullish<T> (as per linked comment above). Great minds think alike!
type TEndpointsPayload = {
getList: undefined;
open: {
id: string;
};
close: {
id: string;
};
};
type OmitNullish<T> = {
[K in keyof T as T[K] extends null | undefined ? never : K]: T[K];
};
type TEndpointsNonEmptyPayload = OmitNullish<TEndpointsPayload>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With