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

两种TypeScript函数类型声明方式的差异及正确写法咨询

两种TypeScript函数类型声明的区别

这两种写法完全不同,核心差异在于类型标注的对象不一样:

1. const example : type = () => {}

这里的type是给变量example本身指定的类型,要求type必须是一个函数类型(比如() => void、(num: number) => string这类描述函数结构的类型)。TypeScript会检查右侧的箭头函数是否匹配type定义的函数结构,不匹配则直接报错。

示例:

// 定义一个无参、返回void的函数类型
type VoidFunc = () => void;
// 给example指定该函数类型,赋值符合结构的函数
const example: VoidFunc = () => { console.log('hello') };

2. const example = () : type => {}

这里的type是给箭头函数的返回值指定的类型,变量example的类型会被TypeScript自动推断为() => type。你只需要保证函数内部的返回值符合type的要求即可。

示例:

// 指定函数返回值为number类型,example会被自动推断为() => number
const example = (): number => { return 123 };

如何为() => {}设置类型?

如果要给这个箭头函数本身指定完整的函数类型,直接用第一种写法即可:要么给变量标注对应的函数类型,要么把函数类型直接写在变量后:

// 直接 inline 标注函数类型
const example: () => string = () => { return 'test' };

// 或者先定义类型再复用
type StringFunc = () => string;
const example: StringFunc = () => { return 'test' };

() : type => {}写法是否正确?

完全正确,这是TypeScript箭头函数中指定返回值类型的标准语法,和普通函数的function(): type {}写法作用一致,只是箭头函数的简化语法形式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:06