#Is there a way to write a HOC w/o double `as`?

1 messages · Page 1 of 1 (latest)

ebon grailBOT
#
onkeltem#0

Preview:```ts
import React, {FC} from "react"

function withFooBar<TOwnProps>(
Component: FC<{foo: string} & TOwnProps>
): FC<{bar: string} & TOwnProps> {
return ({bar, ...ownProps}) => {
return (
<Component
foo={"foo"}
{...(ownProps as unknown as TOwnProps)}
/>
)
}
...```

vale hornet
#

I wonder if there's a way to write a HOC with injections w/o doing double assertion.

#

IIRIC it was always sort of required

#

One doesn't simply write a HOC w/o assertion

vale hornet
#

Finally, here is a reduced example:

ebon grailBOT
#
onkeltem#0

Preview:```ts
import React, {FC} from "react"

type Obj = Record<string, unknown>

function withBar<TOwnProps extends Obj>(
Component: FC<TOwnProps>
): FC<{bar: string} & TOwnProps> {
return ({bar, ...ownProps}) => {
return (
<Component
{...(ownProps as unknown as TOwnProps)}
/>
...```

vale hornet
#

Again, double as: as unknown as TOwnProps

sweet yacht
#

TS is correct to be unhappy about this.

declare const CompA: FC<{ a: string; bar: "x" }>;

Personally, this is probably a case where I'd use an "implementation signature" overload so callers still get the generic signature, but your implementation doesn't have to deal with the generic types:

function withBar<TOwnProps extends {}>(Component: FC<TOwnProps>): FC<{bar: string} & TOwnProps>
function withBar(Component: FC<{}>): FC<{bar: string}> {
  return ({bar, ...ownProps}) => {
    return <Component {...ownProps}/>; 
  };
}
thick mural
#

if you do this, then an exclusive signature like

function withFooBar<TOwnProps extends {}>(Component: "bar" extends keyof TOwnProps ? never : FC<{foo: string} & TOwnProps>): FC<{bar: string} & TOwnProps>

might be a good idea

#

it doesn't help with typing the body, but it does make it more safe