0

Having this implementation

// CustomComponent.ts
type SaveProps = {
    date: string;
    name: string;
}

interface IProps {
    onSave: (props: SaveProps) => void;
}

const CustomComponent = ({onSave}: IProps) => {
    return (
        <button onClick={() => onSave({ date: '', name: '' })}>
            Click me
        </button>
    );
};


// ParentComponent.ts
import CustomComponent from './CustomComponent';

export default function ParentComponent () {
    
    const saveData = props => { // what type is props? how to infer this as SaveProps defined in CustomComponent.ts?
        
    }

    return (
        <CustomComponent onSave={saveData} />
    )
}

How can I infer the type of props in saveData as being Props without having to import the type? So that when reading the props in saveData callback, I would automatically know what kind of data CustomComponent is sending back.

2 Answers 2

1

In most cases, it is better to export Props type along with the component. In your particular case you can do the following:

import { IProps, CustomComponent } from './CustomComponent';

function ParentComponent () {
    const saveData = React.useCallback((props => {
    }) as IProps['onSave'], []);

    return (
        <CustomComponent onSave={saveData} />
    )
}

TS Playground

Sign up to request clarification or add additional context in comments.

2 Comments

yes, importing does makes the deal, but isn't there any other elegant solution? :)
I'll stick with this one
1

Sorry for one more answer. Comments are restricted by max length.

https://www.typescriptlang.org/docs/handbook/type-inference.html#contextual-typing

TS is smart enough to infer types in different directions, And its managed by a bunch of heuristic algorithms. That's why we can not refactor your example according to some generic ruleset (there is no such).

One more trick without explicit export of Props:

(props => {
}) as Parameters<typeof CustomComponent>[0]['onSave']

TS Playground

1 Comment

hmm, yes, that's also a way to go, but much more cumbersome that the "import one"...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.