【问题标题】:Typescript new Date() - 'new' expression, whose target lacks a construct signature, implicitly has an 'any' typeTypescript new Date() - 'new' 表达式,其目标缺少构造签名,隐式具有“any”类型
【发布时间】:2021-12-06 22:56:17
【问题描述】:

我正在尝试使用 new Date() 获取当前时间:

function getTime(): Date{
  const d = new Date()
  return d
}

但这给出了错误:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.

new Date() 与打字稿一起使用的正确方法是什么?

【问题讨论】:

  • 这是正确的方法。您是否在同一文件的某处导入或覆盖了Date
  • 日期有构造函数;事实上,Date 被定义为type DateConstructor。你的代码在我看来是正确的,it works on the Playground。也许您的 Date 导入或类与内置的冲突?

标签: typescript


【解决方案1】:

原来我有冲突,我在我的Date react 组件中使用了new Date()

const Date = (): JSX.Element =>{
  const [date, setDate] = useState(new Date());


  function tick(): void {
    setDate(new Date());
  }

  return(
    <div>
     {date.toLocaleTimeString("en-IT", { hour12: true, timeStyle: "short" })}
    </div>
  )      

}

export default Clock;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2020-04-12
    • 2015-09-22
    • 2018-02-06
    • 2017-03-25
    • 2017-01-29
    • 1970-01-01
    • 2021-01-04
    相关资源
    最近更新 更多