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

TypeScript函数如何添加默认值同时保留类型限制?

解决TypeScript函数参数同时设置类型与默认值的报错问题

你写的代码报错是因为参数默认值和类型注解的顺序搞反了,TypeScript的参数语法要求先写类型注解,再写默认值,不能颠倒。

正确的写法如下:

function greet(name: string = "person") {
  console.log(`Hello ${name}!`);
}

greet("Bob"); // 输出"Hello Bob!"
greet(1); // TypeScript提示类型错误(number类型无法赋值给string类型参数)
greet(); // 输出"Hello person!"

说明

  • 该写法既明确了name必须为string类型,又设置了默认值"person"
  • 不传参数时,函数自动使用默认值;传入非string类型时,TypeScript会在编译阶段抛出类型错误,完全符合你的预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:14:53