ค้นหาเว็บไซต์

typescript - ไม่สามารถใช้ชนิดข้อมูลภายนอกในไฟล์ d.ts ของฉันได้


ฉันต้องการให้ประกาศ interface ทั้งหมดของ TS ของฉันในไฟล์ d.ts ไฟล์เดียว แบบนี้:

interface Iface1 {
   testMethod(): Observable<string>;
}

อย่างไรก็ตาม เมื่อฉันพยายามใช้ประเภทภายนอก (ที่นี่คือ 'Observable' จาก rxjs) คอมไพเลอร์ไม่สามารถระบุได้ว่า 'Observable' คืออะไร

เพิ่มบรรทัด:

/// <reference path="../node_modules/rxjs/observable.d.ts" />

ไปยังส่วนบนของไฟล์ดูเหมือนไม่ช่วยอะไรเลย

ฉันทำอะไรผิดไปหรือ

คำตอบ #1

คุณควรนำเข้า type ของ Observable ในไฟล์ interfaces.d.ts ของคุณ:

///<reference path="../node_modules/rxjs/observable.d.ts" />

import { Observable } from "rxjs/Observable";

ได้รับข้อผิดพลาด Cannot find module 'rxjs/Observable'? ตรวจสอบให้แน่ใจว่าไฟล์ tsconfig.json ของคุณได้ตั้งค่า moduleResolution เป็น "node":

{
  "compilerOptions": {
    "moduleResolution": "node"
  }
}

นี่คือตัวอย่างวิธีนำเข้าอินเทอร์เฟซ:

MyInterfaces.ts

///<reference path="../node_modules/rxjs/observable.d.ts" />

import { Observable } from "rxjs/Observable";

export interface IFoo {
    bar: Observable<number>;
}

แอป.ts

import { IFoo } from "./MyInterfaces"

var myVar : IFoo = {
    bar: null
}

อ่านเพิ่มเติมเกี่ยวกับโมดูลของ Typescript