2017-11-10 14 views
0

TypeオブジェクトからDateオブジェクトの関数を呼び出そうとしていますが、それはできません。私はif/elseでこれをやっていて、他の2つのプリミティブ型を排除しました。 TypeScriptのオブジェクトタイプの使い方がわかりません。 TypeScriptオブジェクトで利用可能な関数はどれも適切ではないようです。 は、ここでは、コードです:Typescriptオブジェクトからオブジェクト関数を呼び出す方法

const formatDate = (date: string | number | object): string | null => { 
 
    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.hasOwnProperty('toISOString')) return date.toISOString(); 
 
    else return null; 
 
}

私はエラーを取得する:

TS2339: Property 'toISOString' does not exist on type 'object'. 

は活字体オブジェクトからオブジェクトの関数を呼び出す方法はありますか?

答えて

0

Typescriptは、日付がランダムなオブジェクトであることだけを示したので、型の安全性を保証することはできません。それを修正するには、Date型を使用するか、必要なメソッドに一致するインターフェイスを作成することができ、次のいずれか

interface hasIsoString { 
    toISOString:() => string 
} 
+0

ああ、私は卵のビデオでそれを見た。私はそれを忘れてしまった。ところで、私はDate型を使用しましたが、同じエラーが発生します。 – kim

+0

もう一度Dateを試しましたが、今は動作します。私はおそらく他のいくつかの問題があったでしょう。 – kim

0

ここでの問題は、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 

はまた、あなたが明示的にこの関数の戻り値の型を指定する必要はありませんいずれの場合にはご注意 - 活字体があなたのためにそれを把握します。

関連する問題