[英]Argument of type 'Date | null' is not assignable to parameter of type 'string'
我只是不明白。
我有這個界面。
export interface Activity {
id: string;
title: string;
date: Date | null;
description: string;
category: string;
city: string;
venue: string;
}
然后我有這個 function:
get activitiesByDate(){
return Array.from(this.activityRegistry.values()).sort((a, b) =>
Date.parse(a.date) - Date.parse(b.date));
}
但我仍然收到此錯誤:
Argument of type 'Date | null' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.ts(2345)
那我做錯了什么? 以及如何糾正?
謝謝
我認為您在這里遇到的錯誤很容易解釋,但我會嘗試更好地解釋:
Javascript 的Date.parse()
方法解析日期的字符串表示,在MDN上有更好的解釋。
這意味着Date.parse()
接受的參數類型必須是string
類型。 它還接受 arguments,它們是 javascript 中的Date
(它是一個對象)的實例。 Date.parse()
返回自 1970 年 1 月 1 日 00:00:00 UTC 以來的毫秒數
例子:
console.log(new Date() instance of Date); // true
console.log(Date.parse(new Date().toString())) // gives the right answer
console.log(Date.parse("01 Jan 1970 00:00:00 GMT")) // works properly
在這種情況下,typescript 告訴您的是,您不應該將類型可能是Date
或 null 的值分配給期望string
類型值的方法。
所以,你可以做什么? 既然您知道Activity
上的變量Date
的類型可能是Date | null
Date | null
我建議你做這樣的事情:
if(a.Date && b.Date) {
Date.parse(a.date.toString()) - Date.parse(b.date.toString()));
}
這是 typescript 超級確保您的代碼是防彈的結果。 在您的界面中,您可能將date
屬性定義為null
。
date: Date | null;
這意味着在這段代碼中:
Date.parse(a.date)
它正在檢查兩種可能性:
Date.parse(null)
或者
Date.parse(<type Date>)
兩者都失敗了。 Date.parse
需要一個string
。 為了讓 typescript 開心,
您需要確保a.date
始終是一個字符串。 This means you need to account for null
and you need to convert your date object to a string, while also accounting for null
when doing the conversion of a date object into a string. 這可以通過可選的鏈接和無效合並來完成
Date.parse(a.date?.toDateString() ?? new Date().toDateString) // or whatever default value you want
但話雖如此,不推薦Date.parse
。 MDN你的用例是什么? 當然,對於實現您的意圖,go 有更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.