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")
来导入此模块。