Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Svelte Reactive Value with Typescript Type

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading