Created
October 23, 2024 19:10
-
-
Save torgeir/930e1c48e77679b51e083f9758a35703 to your computer and use it in GitHub Desktop.
Typescript json cast any to T
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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