在这种情况下
dateToISOString(undefined)
,你只需告诉typescript
undefined
是一个字符串,当调用方试图访问字符串值时,它将导致异常。
相反,你应该处理这个问题
未定义
案例明确,并且(取决于您的用例),您可能希望:
-
返回默认文本:例如“”、“-”等。
-
或者抛出一个错误:例如。
throw Error('undefined date!');
export const dateToISOString = (date: Date | string | undefined): string => {
if (!date) {
/**
* handle the case when the caller passes undefined explicitly.
* Dependent on your use-case you may want to
* - return a default text: e.g. "", "-", etc.
* - or throw Error('undefined date!');
*/
return '-';
} else if (typeof date === "string") {
// then check if the input is a string
return date;
} else {
/**
* now typescript knows that the input is of type Date
* because you defined the input type as: Date | string | undefined
* and you have already handled the undefined and string cases
*/
return dateToStrings(date).toFormat(ISO_DATE_FORMAT);
}
};