Search code examples
javascriptreactjstypescriptreact-typescript

How to add generic type to one of the object's property which Iam getting from Objet destructuring?


This is my line of code:

       const { userName }: { userName: string } = useSelector((s: ReduxType) => s.currentUser.info) || '';

Iam getting this warning " Property 'userName' is missing in type '{}' but required in type '{ userName: string; }"

info is an object which contains following properties

  type userInfo = {
                id: number;
                userName: string;
                userEmail: string;
                created_date: string;
                last_updated: string;
                last_login: string;
                active: boolean;
                fullName: string;
                };

If I use

 const { userName }: any = useSelector((s: ReduxType) => s.currentUser.info) || '';

then warning will disappear but i want to use proper generic type

Thank you in adavnce


Solution

  • use Partial

    const { userName }: Partial<{ userName: string }> = ...