Skip to content

Instantly share code, notes, and snippets.

@torgeir
Created October 23, 2024 19:10
Show Gist options
  • Save torgeir/930e1c48e77679b51e083f9758a35703 to your computer and use it in GitHub Desktop.
Save torgeir/930e1c48e77679b51e083f9758a35703 to your computer and use it in GitHub Desktop.
Typescript json cast any to T
async function typedFetch<T>(): Promise<T> {
let res = await fetch("http://ip.jsontest.com/");
let json = res.json();
return json; // actually Promise<any>
}
type Ip = { ip: String };
(async function () {
let ip = await typedFetch<Ip>();
console.log(ip); // Ip
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment