Home > database >  How to set type for () => dispatch(action) in typescript?
How to set type for () => dispatch(action) in typescript?

Time:12-03

I am new to typescript and converting my jsx to tsx files. How can I define the type for a redux dispatch for my onPress prop? I tried using "Function" and the "AppDispatch". Thanks in advance

import { AppDispatch } from "../redux/store"


interface ItemProps {
    item: Custom_date, 
    onPress: AppDispatch, //What should I put here?
    backgroundColor: any,
    textColor: any
}

const Item = ({ item, onPress, backgroundColor, textColor }: ItemProps) => (
    <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
        <Text style={[styles.dateTitle, textColor]}>{item.title}</Text>
    </TouchableOpacity>
);

export const DateHeader = () => {
    const { date } = useSelector((store: RootState) => store.nutrition)
    const dispatch = useDispatch()
    const renderItem = ({ item }) => {
        const backgroundColor = item.id === date.id ? "#033F40" : "#BDF0CC";
        const color = item.id === date.id ? '#BDF0CC' : '#033F40';

        return (
            <Item
                item={item}
                onPress={() => dispatch(setDate(item))}
                backgroundColor={{ backgroundColor }}
                textColor={{ color }}
            />
        );
    }

    return (<>
        <FlatList {props} />
    </>)
}

CodePudding user response:

The only things you need to know to type a function are the argument types and the return type. In order to find the return type of dispatch() you can check the internals of useDispatch(), but as a general rule (with quite a few exceptions) click handlers will not return anything. Any side effects the function produces, such as by updating a variable or calling an API or updating a database, won't be included in the type signature.

You're also not passing in any parameters in onPress as you can tell from the empty brackets where you define the arrow function, which simplifies things a lot.

As a result your type for onPress will most likely be as follows, if the dispatch function you're calling does not return a value:

interface ItemProps {
    item: Custom_date, 
    onPress: () => void,
    backgroundColor: any,
    textColor: any
}

CodePudding user response:

You should use the type for the dispatch function that you are using in your app, which is most likely the AppDispatch from the Redux store:

interface ItemProps {
    item: Custom_date, 
    onPress: AppDispatch, 
    backgroundColor: any,
    textColor: any
}
  • Related