这里的问题是date 没有将toISOString 作为它自己的属性。 toISOString() 方法附加到 Date 构造函数的原型,而不是任何给定的 Date 对象。
(new Date()).hasOwnProperty('toISOString') //false
Date.prototype.hasOwnProperty('toISOString') //true
不过,您不需要第三次检查来确保类型安全。 Typescript 已经通过消除过程将其视为前两个类型保护之后的日期:
const formatDate = (date: string | number | Date) => {
if (typeof date === 'string') return date ? new Date(date).toISOString() : null;
else if (typeof date == 'number') return date != null ? new Date(date).toISOString() : null;
return date.toISOString();
}
formatDate('2017-11-10'); //"2017-11-10T00:00:00.000Z"
formatDate(1510300800000); //"2017-11-10T00:00:00.000Z"
formatDate(new Date(2017, 10, 10)); //"2017-11-10T00:00:00.000Z"
formatDate({ foo: 'bar' }); //not allowed
但是,如果您要以某种方式使编译后的代码在非 Typescript 环境中可用,理论上您可以像这样更改您的第三次检查,只是为了安全起见:
const formatDate = (date: string | number | Date) => {
if (typeof date === 'string') return date ? new Date(date).toISOString() : null;
else if (typeof date == 'number') return date != null ? new Date(date).toISOString() : null;
else if (date instanceof Date) return date.toISOString();
return null;
}
formatDate('2017-11-10'); //"2017-11-10T00:00:00.000Z"
formatDate(1510300800000); //"2017-11-10T00:00:00.000Z"
formatDate(new Date(2017, 10, 10)); //"2017-11-10T00:00:00.000Z"
formatDate({ foo: 'bar' }); //still not allowed, but would return null if it were
另请注意,在任何一种情况下,您都不需要在此函数上显式指定返回类型 - Typescript 会为您解决。