【问题标题】:Unable to use new Date() in Typescript - TS2554: Expected 1-2 arguments, but got 0无法在 Typescript 中使用 new Date() - TS2554:预期 1-2 个参数,但得到 0
【发布时间】:2022-01-19 14:15:11
【问题描述】:

我正在尝试将 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-fns 来格式化,你可以传入 Date.now() 而不是 new Date()。没见过这个,你用的是什么版本的打字稿?

标签: typescript date constructor


【解决方案1】:

问题是您已将一个名为 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)-&lt;Date&gt;{format(new window.Date())}&lt;/Date&gt;;

【讨论】:

  • 啊,太棒了。奇怪的是,我没有考虑过这个……const DateStyled = styled(Text)` color: #6d6b8c; 确实如此;)
猜你喜欢
  • 2018-05-19
  • 1970-01-01
  • 2020-05-19
  • 2021-07-29
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多