红茶的个人站点

  • 首页
  • 专栏
  • 开发工具
  • 其它
  • 隐私政策
Awalon
Talk is cheap,show me the code.
  1. 首页
  2. 前端学习笔记
  3. 正文

TypeScript 学习笔记 7:模块

2026年2月26日 4点热度 0人点赞 0条评论

导入导出

如果一个 JS 脚本要使用另一个 JS 脚本中的内容,需要导出:

export default function hello() {
    return 'hello world';
}

然后导入:

import hello from './hello.js';
console.log(hello());

这里的export default是默认导出,可以使用import xxx from导入默认导出的内容。

如果报错,可以将tsconfig.json中的verbatimModuleSyntax选项修改为false。

也可以分别导出需要导出的内容:

export const pi = 3.14;
export function square(x: number) {
    return x * x;
}
export function add(a: number, b: number) {
    return a + b;
}

导入:

import {pi,add,square} from './math_utils.js';
console.log(pi);
console.log(add(1,2));
console.log(square(2));

可以使用as为导入的内容指定别名:

import {pi as math_pi,add,square} from './math_utils.js';
console.log(math_pi);

可以使用*将所有分别导出的内容导入到同一个标识符中使用:

import * as math_utils from './math_utils.js';
console.log(math_utils.pi);
console.log(math_utils.add(1,2));
console.log(math_utils.square(2));

虽然不常见,但默认导出和分别导出可以同时使用:

export const DEFAULT_NAME = 'Tom';
export const DEFAULT_AGE = 18;
export class Person {
    name: string;
    age: number;
    constructor(name: string = DEFAULT_NAME, age: number = DEFAULT_AGE) {
        this.name = name;
        this.age = age;
    }
}
export function createPerson(){
    return new Person();
}
export default {
    Person,
    createPerson
}

在导入的时候也可以同时将默认导出和分别导出同时导入:

import person_model,{DEFAULT_NAME,DEFAULT_AGE} from './person.js';
console.log(person_model.createPerson());
console.log(DEFAULT_NAME);
console.log(DEFAULT_AGE);

也可以导入一个 JS 脚本,但不导入任何变量:

import './hello.js';

但通常这样做没有任何意义。

导入类型

在 TS 中,可以导出类型:

interface Animal {
    age: number;
    eat: () => void;
}
​
export interface Dog extends Animal {
    bark: () => void;
}
​
export interface Cat extends Animal {
    meow: () => void;
}
​
export function createDog(): Dog {
    return {
        age: 0,
        bark: () => {},
        eat: () => {}
    };
}

可以像 JS 中那样导入类型:

import {Cat, Dog} from './animal.js'
function playCat(cat: Cat){
    cat.meow();
    cat.eat();
}
​
type Animal = Cat | Dog;

TS 扩展了导入语法,可以用import type导入类型:

import type {Cat, Dog} from './animal.js'

但这种方式只能导入类型,否则会报错:

import type {add as add_func} from './math_utils.js';
add_func(5,6);
// 报错,“add_func”是使用 “import type”导入的,因此不能用作值。

TS 4.5 还允许在分别导入时在导入的标识符前添加type:

import {type Cat, type Dog, createDog} from './animal.js'

在导入时对类型添加 type,有助于一些非 TS 编译器(比如esbuild)知道哪些导入可以被安全移除。

The End.

参考资料

  • TypeScript官方手册

本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: ts
最后更新:2026年2月26日

魔芋红茶

加一点PHP,加一点Go,加一点Python......

点赞
< 上一篇

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2021 icexmoon.cn. ALL RIGHTS RESERVED.
本网站由提供CDN加速/云存储服务

Theme Kratos Made By Seaton Jiang

宁ICP备2021001508号

宁公网安备64040202000141号