Home > other >  Type 'undefined' is not assignable to type 'number' while passing the id
Type 'undefined' is not assignable to type 'number' while passing the id

Time:06-08

I am having an issue whenever I pass the item's id in OnPressItem inside the Text, the (item?.id) shows undefined is not assignable to type 'number. What other way can I declare id is the number?

export interface MeetingListProps {
  data?: Meetings
  style?: StyleProp<ViewStyle>
  onPressItem: (id: number) => void //here define the onPressItem

const { onPressItem } = props
}

const { data, loading, error } = useGetMeetingsQuery
return (
    <View style={styles.container}>
      {data?.meetings &&
        data.meetings.map((item) => {
          return (
            <View>
              <Text style={styles.item} onPress={() => onPressItem(item?.id)}>{item?.title}</Text>
            </View>
          )
        })}
    </View>

CodePudding user response:

When you use optional chaining (?. syntax) the result value can be either your value (item.id) or undefined if the item is null or undefined. So the type of item?.id is number | undefined. The simple solution is to remove the optional chaining operator if your array does not have null-ish values inside, or check for the item before calling the function onPressItem

onPress={() => item ? onPressItem(item.id) : {}}

CodePudding user response:

You should also be able to tell Typescript to expect a number if item exists by supplying a type for item.

export interface MeetingListProps {
  onPressItem: (id: number) => void; //here define the onPressItem
}
type IItem = {
  id: number;
  title: string;
};
type IQuery = () => {
  data: { meetings: IItem[] };
  loading: boolean;
  error: {};
};

const useGetMeetingsQuery: IQuery = () => {
  return { data: { meetings: [] }, loading: true, error: {} };
};

export default function Item(props: MeetingListProps) {
  const { onPressItem } = props;

  const { data, loading, error } = useGetMeetingsQuery();

  return (
    <div>
      {data?.meetings &&
        data.meetings.map((item) => {
          return (
            <div>
              <p onClick={() => onPressItem(item?.id)}>{item?.title}</p>
            </div>
          );
        })}
    </div>
  );
}

Playground

  • Related