Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript Interface string is accepting a number from a fetch

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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

>Solution :

Actually this isn’t about ts. But if you wanna convert your data to string you should use toString() or String(p.user_id)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading