ここでの問題は、date
はは独自のプロパティとしてtoISOString
を持っていないということです。 toISOString()
メソッドは、Date
コンストラクタのプロトタイプに添付されており、指定されたDate
オブジェクトではありません。
(new Date()).hasOwnProperty('toISOString') //false
Date.prototype.hasOwnProperty('toISOString') //true
ただし、型の安全性を確保するために3番目のチェックは必要ありません。しかし、あなたが何らかの形であなたは、非活字体の環境でコンパイルされたコードを利用可能にすることになるだろう、場合
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
:活字体はすでに消去法によって、最初の二つのタイプのガード後の日付として扱います理論的には念のために、そのようなあなたの第三のチェックを変更することができます:
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
はまた、あなたが明示的にこの関数の戻り値の型を指定する必要はありませんいずれの場合にはご注意 - 活字体があなたのためにそれを把握します。
ああ、私は卵のビデオでそれを見た。私はそれを忘れてしまった。ところで、私はDate型を使用しましたが、同じエラーが発生します。 – kim
もう一度Dateを試しましたが、今は動作します。私はおそらく他のいくつかの問題があったでしょう。 – kim