You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
nếu ta có một hàm promise và chưa biết hắn sẽ trả về gì, nhưng ta cần định nghĩa nó để định nghĩa có biến sẽ nhận kết quả trả về của promise đó ta có thể dùng Awaited kết hợp với ReturnType và typeOf
typeGuestInfoPromise=ReturnType<typeoffetchGuestInfo>;typeCheckoutPromise=ReturnType<typeofprocessCheckout>;asyncfunctioncheckoutGuest(guestId: number): Promise<void>{constguestInfo: Awaited<GuestInfoPromise>=awaitfetchGuestInfo(guestId);console.log("Guest information fetched:",guestInfo);awaitprocessCheckout(guestId);console.log("Checkout completed for guest:",guestId);}asyncfunctionfetchGuestInfo(guestId: number): Promise<string>{returnnewPromise<string>((resolve)=>{setTimeout(()=>{resolve(`Guest ${guestId}: John Doe`);},2000);});}asyncfunctionprocessCheckout(guestId: number): Promise<void>{returnnewPromise<void>((resolve)=>{setTimeout(()=>{resolve();},1500);});}constguestId: number=123;checkoutGuest(guestId).then(()=>{console.log("Guest has successfully checked out!");}).catch((error)=>{console.error("An error occurred during checkout:",error);});
trong ví dụ trên, tôi lấy kiểu của promise GuestInfoPromise bằng ReturnType
và dùng Awaited để định nghĩa giá trị trả ra nếu await fetchGuestInfo, một điều thú vị là dù có promise nhiều lớp thì
Awaited vẫn định nghĩa là string
typeA=Awaited<Promise<string>>;// ^? type A = stringtypeB=Awaited<Promise<Promise<number>>>;// ^? type B = number; dù có lồng nhiều lớptypeC=Awaited<boolean|Promise<number>>;// ^? type C = boolean | number;
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Awaited và ReturnType
Awaited vẫn định nghĩa là string
Beta Was this translation helpful? Give feedback.
All reactions