#Is there a more elegant version than this?

10 messages · Page 1 of 1 (latest)

digital briar
#

I want to create a function, that returns an object, and if the includeHtml or includeComponent options are passed to this function, the returned object includes a html and a component property respectfully.

My code works, but it's really hard to read, and feels off. Ideally I'd like to simply type an Options object, and use that, instead of having to use generics for each boolean property I want to use for the return type. Is that possible?

Here is the code (I also added a link to the TS REPL):

type DefaultReturn = {
  default: true
}

export function loadAll<
  TIncludeHtml extends boolean | undefined,
  TIncludeComponent extends boolean | undefined,
>({
  includeHtml = false,
  includeComponent = false,
}: {
  includeHtml?: TIncludeHtml
  includeComponent?: TIncludeComponent
}):
  DefaultReturn
  & (TIncludeHtml extends true ? { html: string } : DefaultReturn)
  & (TIncludeComponent extends true ? { component: string } : DefaultReturn) {
  // I omitted the actual implementation.
  return null as any;
}

const x = loadAll({
  includeHtml: true,
  includeComponent: true,
})
woven stratusBOT
#
enyo#9318

Preview:```ts
const x = loadAll({
includeHtml: true,
includeComponent: true,
})

type DefaultReturn = {
default: true
}

export function loadAll<
TIncludeHtml extends boolean | undefined,
TIncludeComponent extends boolean | undefined

({
includeHtml = false,
includ
...```

woven stratusBOT
#
Ascor8522#7606

Preview:```ts
/**

  • Returns all the keys of T whose values are U.
  • E.g. KeyOfExtends<{ a: false, b: true }, true> => "b"
    */
    type KeyOfExtends<T, U> = keyof {
    [K in keyof T as T[K] extends U ? K : never]: T[K];
    };

/**

  • Transform an union type into an intersection.
    ...```
mild vigil
#

@digital briar

#

once you break down the problem into smaller pieces, it becomes way easier

#

first, select only the keys you want on the object

#

then maps them onto the second object

#

don't forget you can always create your own utility types, and reuse them in other placces

digital briar
#

Wow thanks!

mild vigil
#

!resolved