MST

星途 面试题库

面试题:TypeScript中import和export的基础用法

请描述在TypeScript中如何使用export导出一个函数和一个接口,以及如何使用import导入它们。假设你有一个名为`mathUtils.ts`的文件,其中定义了一个`add`函数和`MathOperation`接口,在另一个`main.ts`文件中导入并使用它们。
11.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

mathUtils.ts 中导出函数和接口

// mathUtils.ts
// 定义接口
export interface MathOperation {
    (a: number, b: number): number;
}

// 定义函数
export function add(a: number, b: number): number {
    return a + b;
}

main.ts 中导入并使用

// main.ts
// 导入接口和函数
import { MathOperation, add } from './mathUtils';

// 使用导入的函数
const result: number = add(5, 3);
console.log(result);

// 可以使用接口来定义变量类型
let operation: MathOperation = add;
let newResult: number = operation(10, 20);
console.log(newResult);