I have a function that takes in a string and based on the string hits different APIs to fetch images.
I have solved it by writing an interface and then as the return type of the function, it returns a Promise<Interface>
as shown in the code below.
interface IAnimal {
image?: string | null
message?: string
status: string
}
const getAnimal = async (inAnimal: string): Promise<IAnimal> => {
const isDogWord: boolean = ["dog", "Dog", "DOG"].includes(inAnimal.trim())
const isFoxWord: boolean = ["fox", "Fox", "FOX"].includes(inAnimal.trim())
let result: IAnimal = { image: null, status: "tofetch" };
if(isDogWord) {
result = await fetch("https://dog.ceo/api/breeds/image/random").then((data) => data.json());
if(result.status === "success") {
return {
image: result.message,
status: result.status
}
}
}
if(isFoxWord) {
result = await fetch("https://randomfox.ca/floof/").then((data) => data.json());
return {
image: result.image,
status: "success"
}
}
return {
image: null,
status: "failure"
}
};
This solves the typescript errors but I am not happy with making the image and message optional in the Interface. I am receiving { "message": "image__link", "status": "success or failure" }
from dog API and {"image": "image__link", "status": "success or failure"}
from the fox API. Is what I have done the right approach or do we have a better solution.