typescript types with Promise

Viewed 986

I'm still relatively new to typescript and I cannot figure out how to add types to a function that use a Promise.

I follow the suggestion from Typescript and make my function Props from UserStateProps to Promise<UserStateProps> but now is complaining that this Promise<UserStateProps> is missing the necessary properties.

I have this function:

    const mergeCookiesWithUserState = async (defaultUserState: UserStateProps): Promise<UserStateProps>  => {
  const newUserState = { ...defaultUserState }

  for (const key in newUserState) {
    if (Object.getOwnPropertyDescriptor(cookiesName, key)) {
      const cookieValue = await getCookieValue(cookiesName[key])

      console.log({ cookieValue})
      if (cookieValue !== undefined) {
        newUserState[key] = cookieValue
      }
    }
  }
    
  return newUserState
}

which I use to update the React state. The react user state uses UserStateProps to check the state types. Since when I introduced a Promise in the mergeCookiesWithUserState, the user state complained about its props:

Type 'Promise<UserStateProps>' is missing the following properties from type 'UserStateProps': numOfSearches, language, adultContentFilter, openInNewTab, isModalOpents(2739)

These are the interface:

export interface UserStateProps {
 

 numOfSearches: number
  language: number
  adultContentFilter: number
  openInNewTab: boolean
  isModalOpen: boolean
}
export interface UserContextProps {
  userState: UserStateProps
  setUserState: (userState: Partial<UserStateProps>) => void
}

Anyone can help me out to understand this thing?

UPDATE: it turned out that the problem was how I have written getCookieValue() and therefore how to handle the returned Promised from it. But all your comments put me on the right track again to figure out the solution. I believe the answer I sign as correct, is the most pertinent one for the error I got and the async nature of my problem. Thanks!

1 Answers
Type 'Promise<UserStateProps>' is missing the following properties from type 'UserStateProps'

That means that somewhere in your code you did:

const example: UserStateProps = mergeCookiesWithUserState()

Along with that you specifically told your function type to return Promise<UserStateProps> which you're trying to assign to UserStateProps.

You can't assign a promise to UserStateProps.

The promise is there because of the fact that your function is marked async which will automatically return a promise with whatever value it should return as the type of the promise, which it will eventually resolve to.

const example: UserStateProps = await mergeCookiesWithUserState()

That's all you need to fix your error, the await keyword will let the promise resolve before assigning the value to example.

Related