node.jstypescriptdiscord.jsnode-fetch

Property 'uuid' does not exist on type 'unknown'.ts(2339)


This is for a Discord bot and the error pops up when trying to fetch api data. It should reply with the fetched uuid but the bot can't even start since the error pops up on start. Code:

import fetch from "node-fetch";

export default {
    callback: async (message: Message, ...args: string[]) => {

        fetch('https://api.ashcon.app/mojang/v2/user/' + args)
        .then(response => response.json())
        .then(data => {
            let uuid = data.uuid
            message.reply("uuid: " + uuid)
        })
    }
}

Error: Property 'uuid' does not exist on type 'unknown'.ts(2339)


Solution

  • Error happens because typescript does not know what type of data you fetched;

    You need to manually specify type of data using as.

    Or, you can use libraries like zod and joi for validation and auto type inferring.