typescirpt - .d.ts聲明文件的用法


1、如果是可調用的方法,需要像下面這樣聲明:

declare function myLib(a: string): string;
declare function myLib(a: number): number;

調用的時候像這樣: 

myLib(3)

2、如果希望此庫的名稱是有效的類型名稱:

interface myLib {
    name: string;
    length: number;
    extras?: string[];
}

你調用的時候會這樣:

var x: myLib

3、如果您的庫具有在全局變量上公開的屬性:

declare namespace myLib {
    //~ We can write 'myLib.timeout = 50;'
    let timeout: number;

    //~ We can access 'myLib.version', but not change it
    const version: string;

    //~ There's some class we can create via 'let c = new myLib.Cat(42)'
    //~ Or reference e.g. 'function f(c: myLib.Cat) { ... }
    class Cat {
        constructor(n: number);

        //~ We can read 'c.age' from a 'Cat' instance
        readonly age: number;

        //~ We can invoke 'c.purr()' from a 'Cat' instance
        purr(): void;
    }

    //~ We can declare a variable as
    //~   'var s: myLib.CatSettings = { weight: 5, name: "Maru" };'
    interface CatSettings {
        weight: number;
        name: string;
        tailLength?: number;
    }

    //~ We can write 'const v: myLib.VetID = 42;'
    //~  or 'const v: myLib.VetID = "bob";'
    type VetID = string | number;

    //~ We can invoke 'myLib.checkCat(c)' or 'myLib.checkCat(c, v);'
    function checkCat(c: Cat, s?: VetID);
}

 如果是nodejs的文件,即在node服務上執行的js使用到了 global

// index.d.ts
// nodejs中用到 global.cache = {},需要聲明global
declare module NodeJS {
    interface Global {
        cache: Object;
    }
}

如何聲明window.xxx全局變量

// index.d.ts
interface Window {
   //在這里聲明xxx之后就能在文件中 window.xxx這樣調用了
    xxx: any;
    
}

declare interface Window {
  process: {
    env: {
      NODE_ENV: 'development' | 'production';
    };
  };
  ShareCommponent: {
    showSharePanle: (options: ShareArg) => void;
  };
  LANG: string;
}

 

聲明 .scss和 .less文件

// index.d.ts
declare module '*.scss' {
    const content: { [key: string]: any };
    export default content;
}

declare module '*.less' {
    const content: { [key: string]: any };
    export default content;
}

聲明圖片

// index.d.ts
declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.gif'
declare module '*.bmp'
declare module '*.tiff'

如果需要引入一些不按照模塊化寫的文件

// index.d.ts
declare module 'core-js/modules/es7.promise.finally';

//這樣聲明之后就可以估文件中引用
//demo.ts
import 'core-js/modules/es7.promise.finally';

 node核心模塊如何引入,注意這里不需要在.d.ts文件里面聲明 

import path = require('path')

 

export = 和 import = require()

CommonJS和AMD的環境里都有一個exports變量,這個變量包含了一個模塊的所有導出內容。

CommonJS和AMD的exports都可以被賦值為一個對象, 這種情況下其作用就類似於 es6 語法里的默認導出,即 export default語法了。雖然作用相似,但是 export default 語法並不能兼容CommonJS和AMD的exports

為了支持CommonJS和AMD的exports, TypeScript提供了export =語法。

export =語法定義一個模塊的導出對象。 這里的對象一詞指的是類,接口,命名空間,函數或枚舉。

若使用export =導出一個模塊,則必須使用TypeScript的特定語法import module = require("module")來導入此模塊。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM