I'm trying to get a timestamp from a Date object in Svelte and TypeScript. I want the timestamp to update whenever the Date object is updated, so I'm trying to make it reactive. Here's the code I tried:
let date: Date = new Date();
$: timestamp: string = date.getHours() ':' date.getMinutes() ":"
date.getSeconds(); // timestamp in format hh:mm:ss
But I'm getting this error from TypeScript: 'string' only refers to a type, but is being used as a value here.
. If I remove the type, then everything works. I think multiple meanings of a colon is confusing the compiler but I'm not sure. Is there any way I can do this while keeping the type?
CodePudding user response:
There's no reason to do this in this case, since TypeScript will infer the type string
, but if you ever need to do this with a more complex type, do this:
let timestamp: string;
$: timestamp = date.getHours() ':' date.getMinutes() ":"
date.getSeconds(); // timestamp in format hh:mm:ss
this is in the svelete typescript docs