MST

星途 面试题库

面试题:TypeScript中接口与类型别名在函数定义上的区别

请阐述在TypeScript里,使用接口和类型别名来定义函数类型时,有哪些不同点,并分别给出示例代码。
29.0万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

不同点

  1. 扩展方式
    • 接口:可以通过 extends 关键字继承其他接口,从而扩展接口定义。
    • 类型别名:使用交叉类型 & 来扩展类型别名。
  2. 重复定义
    • 接口:允许重复定义,后续定义会与之前的合并。
    • 类型别名:不允许重复定义,重复定义会报错。
  3. 适用场景
    • 接口:更适合面向对象编程风格,用于定义对象的形状和契约。
    • 类型别名:功能更通用,除了定义函数类型,还能定义联合类型、交叉类型等复杂类型。

示例代码

接口定义函数类型

// 定义一个接口来描述函数类型
interface AddFunction {
    (a: number, b: number): number;
}

// 使用接口定义函数
const add: AddFunction = (a, b) => a + b;

类型别名定义函数类型

// 使用类型别名定义函数类型
type MultiplyFunction = (a: number, b: number) => number;

// 使用类型别名定义函数
const multiply: MultiplyFunction = (a, b) => a * b;

接口扩展示例

interface BaseFunction {
    (): void;
}
interface ExtendedFunction extends BaseFunction {
    (value: string): void;
}

const extendedFunc: ExtendedFunction = (value?) => {
    if (value) {
        console.log(value);
    } else {
        console.log('No value');
    }
};

类型别名扩展示例

type BaseType = () => void;
type ExtendedType = BaseType & ((value: string) => void);

const extendedTypeFunc: ExtendedType = (value?) => {
    if (value) {
        console.log(value);
    } else {
        console.log('No value');
    }
};

接口重复定义示例

interface RepeatableFunction {
    (a: number): number;
}
interface RepeatableFunction {
    (b: string): string;
}
// 这里接口定义合并,RepeatableFunction 现在可以接受 number 或 string 参数
const repeatableFunc: RepeatableFunction = (arg) => {
    if (typeof arg === 'number') {
        return arg * 2;
    } else {
        return arg + arg;
    }
};

类型别名重复定义示例(会报错)

// 报错:标识符 'DuplicatedType' 已经被声明。
type DuplicatedType = (a: number) => number;
type DuplicatedType = (b: string) => string;