skip to Main Content

I am loading data from a fetch in TS and attempting to set a value which should be a string but instead is a number.

The interface

export default interface IPost {
    id: number;
    title: string;
    content: string;
    imageUrl: string;
    user_id: string;
  }

My attempt at loading the values from the fetch

.then((data: IPost[]) => {
        console.log("POST DATA", data);
        const posts = data.map((p:IPost) => {
          const post: IPost = {
            id: p.id,
            title: p.title,
            content: p.content,
            imageUrl: p.imageUrl,
            user_id: p.user_id//thinks its a string but its actually a number
            //need to fix this for now just make it a string
          }
          console.log('post map', post, typeof post.user_id)
          return post
        })
      })

When I console log the user_id it is a number even though the interface requires a string. What I have tried is replacing user_id: p.user_id with user_id: p.user_id.toString(). This does work but I wondered why does TS accept a number as a string shouldn’t it throw an error or not accept the value.
Thanks

2

Answers


  1. const post: IPost = {
      id: p.id,
      title: p.title,
      content: p.content,
      imageUrl: p.imageUrl,
      user_id: String(p.user_id)
    }
    
    Login or Signup to reply.
  2. Actually this isn’t about ts. But if you wanna convert your data to string you should use toString() or String(p.user_id)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search