这是我参与更文挑战的第8天,活动详情查看: 更文挑战
模块
TypeScript与ECMAScript 2015一样,任何包含顶级import或者export的文件都被当成一个模块。相反地,如果一个文件不带有顶级的import或者export声明,那么它的内容被视为全局可见的(因此对模块也是可见的)。
导出
导出声明
任何声明(比如变量,函数,类,类型别名或接口)都能够通过添加export关键字来导出。
export interface Person {
name: string
age: number
}
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
导出语句
导出语句很便利,因为我们可能需要对导出的部分重命名,所以上面的例子可以这样改写:
class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export { ZipCodeValidator };
export { ZipCodeValidator as mainValidator };
或者一个模块可以包裹多个模块,并把他们导出的内容联合在一起通过语法:export * from "module"。
export * from "./StringValidator"; // exports interface StringValidator
export * from "./LettersOnlyValidator"; // exports class LettersOnlyValidator
export * from "./ZipCodeValidator";
导入
import { ZipCodeValidator } from "./ZipCodeValidator";
const myValidator = new ZipCodeValidator()
也可以对导入内容重命名
import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
let myValidator = new ZCV();
将整个模块导入到一个变量,并通过它来访问模块的导出部分
import * as validator from "./ZipCodeValidator";
let myValidator = new validator.ZipCodeValidator();
默认导出
export default class Person {...}
import Person from "./Person.ts"
export = 和 import = require()
CommonJS和AMD的环境里都有一个exports变量,这个变量包含了一个模块的所有导出内容。
CommonJS和AMD的exports都可以被赋值为一个对象, 这种情况下其作用就类似于 es6 语法里的默认导出,即 export default语法了。虽然作用相似,但是 export default 语法并不能兼容CommonJS和AMD的exports。
为了支持CommonJS和AMD的exports, TypeScript提供了export =语法。
若使用export =导出一个模块,则必须使用TypeScript的特定语法import module = require("module")来导入此模块。
ZipCodeValidator.ts
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
export = ZipCodeValidator;
Test.ts
import zip = require("./ZipCodeValidator");
// Some samples to try
let strings = ["Hello", "98052", "101"];
// Validators to use
let validator = new zip();
// Show whether each string passed each validator
strings.forEach(s => {
console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
});
外部模块简写
假如你不想在使用一个新模块之前花时间去编写声明,你可以采用声明的简写形式以便能够快速使用它。
declarations.d.ts
declare module "hot-new-module";
简写模块里所有导出的类型将是any。
import x, {y} from "hot-new-module";
x(y);