#Assign complex type inside generic rather than duplicating it?

12 messages · Page 1 of 1 (latest)

wide totem
#

In the following function type, I use Omit<TComponent, 'onClose'> multiple types. Is there a way I can "assign" that a type somewhere (inside the generic maybe?) so that I can have a reusable type rather than declare that twice?

export type WindowOpenFunction = <TComponent extends Closeable>(
  window: ComponentType<TComponent>,
  ...args: keyof Omit<TComponent, 'onClose'> extends never ? [] : [Omit<TComponent, 'onClose'>]
) => TComponent extends Closeable<infer R> ? Promise<R> : Promise<undefined>
ebon trellis
#

Technically, I've seen generic params used for this:

export type WindowOpenFunction = <
    TComponent extends Closeable,
    PropsWithoutClose = Omit<TComponent, 'onClose'>
> = /*...*/

... but I'd be a bit skeptical about doing this in a public type (I guess could define a 'private' internal type that the external one uses?)

#

And honestly the only place I think I've seen this is in the Redux/RTK codebase which has some very complex types.

#

I generally just repeat things.

wide totem
#

I tried that, but wouldn't that conflict with the second parameter? I'm learning ts generics but when I tried to do that it broke everything

ebon trellis
#

What do you mean by "conflict with the second parameter"?

wide totem
#

So ts can infer the first generic from the type of the first function parameter, is that not true for the second generic and second parameter?

ebon trellis
#

Oh, I missed that this is a function, yeah, you probably shouldn't do that.

#

You can probably get away with these sort of 'renaming' params, on a type itself:

type MyType<T, U = /* something calculated from T */> = 

since TS never infers those params.

wide totem
#

where would that go in this function type?

#

or I guess I'm not following how that's different

ebon trellis
#

It's a different construct; I don't think you can apply this trick to a function type easily.