无法在 Typescript 中使用 new Date() - TS2554:需要 1-2 个参数,但得到 0 个

Unable to use new Date() in Typescript - TS2554: Expected 1-2 arguments, but got 0

我正在尝试将 js 日期与 Ts 一起使用,但似乎无法。

用法

<Date variant="body2">on {format(new Date(), 'dd/MM/yyyy')}</Date>

错误

Expected 1-2 arguments, but got 0.  TS2554

  > 162 |             <Date variant="body2">on {format(new Date(), 'dd/MM/yyyy')}</Date>
        |                                              ^
    163 |           </>
    164 |         )}
    165 |       </UploadBox>

问题是您已将名为 Date 的 React 组件导入范围并隐藏了内置 Date 对象。您的代码可能 如下所示:

import { Date } from 'some/ui/library';

// ... snip ...
function MyCoolComponent(props) {
  return <Date>{format(...)}</Date>;
}

如果您想访问全局 Date 对象,您需要 :

  • 以另一种方式导入组件(例如import { Date as DateElement } from 'some/ui/library';
  • 从全局访问全局 Date 对象(使用 windowglobalThis)- <Date>{format(new window.Date())}</Date>;