TypeScript 中如何正确声明一个可选的函数参数?
我在写一个工具函数,想让某个参数是可选的,但 TS 一直报错说类型不匹配。我试过用 param?: string,但调用时传 undefined 还是提示错误,是不是哪里写错了?
比如下面这个函数:
function greet(name: string, title?: string) {
return title ? <code>${title} ${name}</code> : name;
}
当我这样调用 greet('Alice', undefined) 时,TS 就报错:“Argument of type ‘undefined’ is not assignable to parameter of type ‘string | undefined’.” 这不就矛盾了吗?
title: string | undefined就行了。改成这样: