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

TypeScript是否支持自定义函数类型定义?示例解析

是的,TypeScript完全支持自定义可复用的函数类型!

你给出的用type别名定义函数类型的写法完全正确,这正是TypeScript中复用函数类型的常用方式之一。

先确认你的代码是可以正常工作的:
首先定义基础的Person接口:

interface Person { 
  first: string; 
  last: string; 
}
const obj: Person = { first: 'John', last: 'Thomas'};

然后用type定义可复用的函数类型:

type PersonLogger = (p: Person) => void;

const Fun1: PersonLogger = (p) => { 
  console.log('first function', JSON.stringify(p)) 
};
const Fun2: PersonLogger = (p) => { 
  console.log('second function', JSON.stringify(p)) 
};

Fun1(obj); // 输出: first function {"first":"John","last":"Thomas"}
Fun2(obj); // 输出: second function {"first":"John","last":"Thomas"}

除了type别名,你还可以用interface来定义函数类型,写法稍有不同但效果一致:

interface PersonLogger {
  (p: Person): void;
}

// 用法和type别名的方式完全一致
const Fun3: PersonLogger = (p) => {
  console.log('third function', JSON.stringify(p));
};
Fun3(obj);

两种定义方式的小差异

  • type别名更灵活,支持联合类型、交叉类型等复杂场景;
  • interface支持后续代码的合并扩展(比如如果需要给这个函数类型额外添加属性,用interface会更方便)。

总之,你提出的复用函数类型的思路完全符合TypeScript的设计逻辑,这也是TypeScript类型系统中复用类型定义的核心场景之一。

内容的提问来源于stack exchange,提问作者Akshay Vijay Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:57:29