You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript接口是否支持函数默认实现?附编译失败示例

TypeScript接口是否支持函数默认实现?

首先明确:TypeScript 不支持直接在接口中为方法定义默认实现,你提供的示例代码编译失败正是因为违反了接口的语法规则——接口仅用于定义类型签名(方法名、参数、返回值),不能包含具体的函数实现逻辑,示例里的= { console.log(...) }写法完全不符合接口的语法规范。

如果需要实现类似“方法默认实现”的效果,有两种常用的替代方案,适配你使用的TypeScript 5.5.3版本:

方案1:使用抽象类替代接口

抽象类既可以定义抽象方法(仅签名),也可以包含带有默认实现的方法,子类可以选择重写默认实现,或者直接继承使用:

abstract class Greeting {
    // 带有默认实现的方法
    sayGoodbye(name: string): void {
        console.log(`Goodbye, ${name}!`);
    }

    // 抽象方法,子类必须实现
    abstract sayHello(name: string): void;
}

class EnglishGreeting extends Greeting {
    // 可选:重写默认的sayGoodbye方法
    // sayGoodbye(name: string): void {
    //     throw new Error("Method not implemented.");
    // }

    // 必须实现抽象方法sayHello
    sayHello(name: string): void {
        console.log(`Hello, ${name}!`);
    }
}

// 测试:调用默认实现
const greeting = new EnglishGreeting();
greeting.sayGoodbye("Alice"); // 输出: Goodbye, Alice!

方案2:接口 + 独立默认实现函数

先定义接口规范,再单独编写默认实现函数,类可以选择复用该函数来减少重复代码:

interface Greeting {
    sayGoodbye(name: string): void;
    sayHello(name: string): void;
}

// 定义默认实现函数
const defaultSayGoodbye: Greeting['sayGoodbye'] = (name) => {
    console.log(`Goodbye, ${name}!`);
};

class EnglishGreeting implements Greeting {
    // 复用默认实现
    sayGoodbye = defaultSayGoodbye;

    sayHello(name: string): void {
        console.log(`Hello, ${name}!`);
    }
}

// 测试
const greeting = new EnglishGreeting();
greeting.sayGoodbye("Bob"); // 输出: Goodbye, Bob!

总结:接口本身不能写默认实现,但可以通过抽象类或者接口配合独立默认函数的方式,达到类似的效果。

内容的提问来源于stack exchange,提问作者user17435581

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 14:12:38