TypeScript Tutorial in Hindi #40 - Typed Promise | TypeScript with Async Code

Typed Promise in TS

What is Promise ?

A Promise in TypeScript is an object that represents the eventual completion (success) or failure of an asynchronous operation and allows handling of the result or error once the operation finishes


How to define type for promise.

Define Custom type in promise.

Interview Question


promise.ts

interface resultType{
name:string,
id:number,
email:string
}

interface resultType2{
name:string,
id2:number,
}


function complexLogic():Promise<resultType> {
return new Promise((resolved)=>{
setTimeout(() => {
resolved({
name:'anil',
id:10,
email:'anil@codestepbystep'
})
}, 2000);
})
}

async function handlePromise() {
try {
const result = await complexLogic();
console.log(result);
} catch (error) {
console.error("Error:", error);
}
}
handlePromise();


promise.js

"use strict";
function complexLogic() {
return new Promise((resolved) => {
setTimeout(() => {
resolved({
name: 'anil',
id: 10,
email: 'anil@codestepbystep'
});
}, 2000);
});
}
async function handlePromise() {
try {
const result = await complexLogic();
console.log(result);
}
catch (error) {
console.error("Error:", error);
}
}
handlePromise();