Home > Enterprise >  Best practices for returning a variable Omit return value from function?
Best practices for returning a variable Omit return value from function?

Time:09-21

I have a function that originally had a return type of

Promise<Record<
ReturnType,
Omit<SomeInterface, 'key1' | 'key2'>>>

i.e. previously we knew that key2 would always be omitted.

Now, the function should return the same type, but key2 may or may not be omitted. Is there some way to do this, such as

Promise<Record<
ReturnType,
Omit<SomeInterface, 'key1' | 'key2'>> |
Record<
ReturnType,
Omit<SomeInterface, 'key1'>>>

CodePudding user response:

Try this:

type OptionalProperty<O, K extends keyof O> = Pick<Partial<O>, K> & Omit<O, K>;
type T = Promise<Record<ReturnType, OptionalProperty<Omit<SomeInterface, 'key1'>, 'key2'>>>;

CodePudding user response:

After Omiting it, you can add it back as an optional property.

Something like:

Promise<
  Record<
    ReturnType,
    Omit<SomeInterface, 'key1' | 'key2'> & { key2?: SomeInterface['key2'] }
  >
>
  • Related