【问题标题】:Svelte Reactive Value with Typescript TypeTypescript 类型的 Svelte 反应值
【发布时间】:2022-08-23 22:16:46
【问题描述】:

我试图从 Svelte 和 TypeScript 中的 Date 对象中获取时间戳。我希望在 Date 对象更新时更新时间戳,因此我试图使其具有反应性。这是我尝试过的代码:

let date: Date = new Date();
$: timestamp: string = date.getHours() + \':\' + date.getMinutes() + \":\" + 
    date.getSeconds(); // timestamp in format hh:mm:ss

但是我从 TypeScript 收到了这个错误:\'string\' only refers to a type, but is being used as a value here.。如果我删除类型,那么一切正常。我认为冒号的多重含义使编译器感到困惑,但我不确定。有什么办法可以在保持类型的同时做到这一点?

  • 您正在过度使用类型定义。 TypeScript 将推断类型。就做let date = new Date(); $: timestamp = date.getHours() + ... + date.getSeconds();

标签: typescript svelte


【解决方案1】:

在您的情况下没有理由这样做,因为 TypeScript 将推断类型 string

但是根据Svelte TypeScript docs,如果您需要使用更复杂的类型执行此操作,请执行以下操作:

let timestamp: string;
$: timestamp = date.getHours() + ':' + date.getMinutes() + ":" + 
    date.getSeconds(); // timestamp in format hh:mm:ss

【讨论】:

    猜你喜欢
    • 2021-06-12
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2018-03-13
    • 2020-07-04
    • 2018-12-11
    相关资源
    最近更新 更多