felixyadomi
felixyadomi

Reputation: 3396

How to reuse function type inside a component for other components props

How can I declare my props to use a type definition of a function declared inside another component ?

In the example below, how can I tell onUpdate to be the same definition as the onUpdate function defined in index.js ?

// index.tsx
interface UIState {
    position: number
}

const Provider = () => {
    const onUpdate = <T extends keyof UIState>(property: T, fn: (ui: UIState) => UIState[T]): void => {
        // some cool function logic here..
    }

    return <Entry onUpdate={onUpdate} />
}


// Entry.tsx
const Entry = ({ onUpdate }: { onUpdate: /* ??? */) => {
    const onClick = () => {
        onUpdate('position', ui => ui.position + 1);
    }

    return <div onClick={onClick} ></div>;
}

Of course I could reuse the same definition, but meh. that's just straight duplication

const Entry = ({ onUpdate }: { onUpdate: <T extends keyof UIState>(property: T, fn: (ui: UIState) => UIState[T]) => void }) => {    

Should I declare the function definition outside the component ? If so, how ?

Upvotes: 0

Views: 45

Answers (1)

Abdelmonaem Shahat
Abdelmonaem Shahat

Reputation: 544

make it a type to reuse it again and again like this:

type TUpdateFn<T extends keyof UIState> = (property: T, fn: (ui: UIState) => UIState[T]) => void

and use it like this:

const Entry = ({onUpdate}:{onUpdate: Tupdate}) => {
 // your logic here
}

Upvotes: 2

Related Questions