javascript - วิธีใช้ Bluebird ใน Typescript 2.1+
(ฉันได้อ่านโพสต์นี้แล้ว แต่เป็นโพสต์จากเดือนสิงหาคม และมันไม่ได้ตอบคำถามของฉันสำหรับเวอร์ชัน TypeScript ปัจจุบัน)
ฉันกำลังใช้ Typescript 1.8 ในโครงการของฉันอยู่ตอนนี้และสิ่งนี้ใช้งานได้ดี:
import * as Promise from "bluebird";
async function f() : Promise<void> {
return Promise.delay(200);
}
แต่ถ้าฉันพยายามคอมไพล์ด้วย Typescript 2.1:
index.ts(2,16): error TS1059: Return expression in async function does not have a valid callable 'then' member.
เมื่อค้นหาปัญหาเกี่ยวกับการใช้ Bluebird Promises ใน Typscript ด้วยการค้นหาใน Google ฉันยังพบการอภิปรายมากมายใน GitHub ความคิดเห็นและ PRs แต่ทั้งหมดนั้นยากต่อการเข้าใจ และในขณะที่มีการพูดคุยเกี่ยวกับประเด็นที่น่าสนใจ ฉันก็ไม่สามารถหาที่ไหนได้เลยที่บอกว่าฉันควรทำให้มันทำงานได้อย่างไรตอนนี้
แล้วฉันควรจะสามารถใช้ Bluebird สำหรับ Promises ใน Typescript 2.1 ได้อย่างไร?
คำตอบ #1
พิจารณาการใช้ @types/bluebird-global ดังนี้
npm install --save-dev @types/bluebird-global
นำเข้านี้เพียงครั้งเดียวในจุดเข้าหลักของคุณ
// The same Promise API, everywhere.
import * as Promise from 'bluebird'
global.Promise = Promise
ดูประเด็น DefinitelyTyped หมายเลข #11027 สำหรับบริบทเพิ่มเติม
คำตอบ #2
ฉันถามคำถามเดียวกันที่นี่: https://github.com/Microsoft/TypeScript/issues/8331
สุดท้ายคำตอบของฉันเองก็ใช้ได้ นี่คือวิธีการใช้ใน TypeScript 2.3 โดยไม่ต้องมีไฟล์ .d.ts เพิ่มเติม:
import * as Bluebird from 'bluebird';
export interface DummyConstructor extends Bluebird<any> {
new<T>(): Bluebird<T>;
}
declare global {
interface Promise<T> extends Bluebird<T> {
then(...args: any[]): any;
catch(...args: any[]): any;
}
interface PromiseConstructor extends DummyConstructor {}
var Promise: Promise<any>;
}
Promise = Bluebird as any;
async function test() {
console.log('PING');
await Promise.delay(1000);
console.log('PONG');
}
test();
มันแย่มากและจะไม่ทำงานในอนาคตเมื่อมุ่งเป้าไปที่ ES7 แบบเนทีฟ เพราะในอนาคต async/await จะไม่คืนค่า Bluebird promises และไม่สามารถทำอะไรกับเรื่องนั้นได้ อย่างไรก็ตาม จนกว่าจะถึงตอนนั้น และเมื่อแปลงโค้ดเป็น ES5 วิธีนี้จะยังคงใช้งานได้
แม้ว่าจะมีหลายประเภท any ดูเหมือนว่าจะปลอดภัยต่อประเภทบ้าง ฉันมั่นใจว่าสามารถปรับปรุงได้
