Facing compilation issues when using Typescript with Svelte

My project was set up using npm create svelte@latest, with ts enabled and tailwind added.

However, when declaring

<script lang="ts">
, I encountered an Unexpected Token error, like the one below:

D:/gits/rpg-board/src/lib/components/FilterBar.svelte:3:12 Unexpected token
 1 |  <script lang="ts">"use strict";
 2 |  class Greeter {
 3 |      greeting;
                  ^
 4 |      constructor(message) {
 5 |          this.greeting = message;
\r\n\r\n
WatWat

\r\n"}, node_ids: [0, 1], params: {}, routeId: "deck", data: (function(a){return [a,a]}(null)), errors: null }, paths: {"base":"","assets":""}, target: document.querySelector('[data-sveltekit-hydrate="1regxrp"]').parentNode, trailing_slash: "never" });

The repository can be found here: https://github.com/FurtherUnspecified/rpg-board/commit/8ce8eed599bf042f1d8ccd6db2d57456e6d7f15c

I am unsure of what I may have missed in the setup configuration.

Below is the full log of the Svelte project initialization process:

PS D:\gits> npm init vite
√ Project name: ... rpg-board
√ Select a framework: » Svelte
√ Select a variant: » SvelteKit
Need to install the following packages:
  <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="95f6e7f0f4e1f0b8e6e3f0f9e1f0d5a7bba5bba5b8fbf0ede1bba4a2a7">[email protected]</a>
Ok to proceed? (y) y

create-svelte version 2.0.0-next.172

Welcome to SvelteKit!

This is beta software; expect bugs and missing features.

Problems? Open an issue on https://github.com/sveltejs/kit/issues if none exists already.

√ Directory not empty. Continue? ... yes
√ Which Svelte app template? » Skeleton project
√ Add Prettier for code formatting? ... No / Yes
√ Add Playwright for browser testing? ... No / Yes

Your project is ready!
✔ Typescript
  Inside Svelte components, use <script lang="ts">
✔ ESLint
✔ Prettier
  https://prettier.io/docs/en/options.html
  https://github.com/sveltejs/prettier-plugin-svelte#options
✔ Playwright
  https://playwright.dev

Install community-maintained integrations:
  https://github.com/svelte-add/svelte-adders

Next steps:
  1: cd rpg-board
  2: npm install (or pnpm install, etc)
  3: git init && git add -A && git commit -m "Initial commit" (optional)
  4: npm run dev -- --open

To close the dev server, hit Ctrl-C

Stuck? Visit us at https://svelte.dev/chat

Despite this setup, I am still unable to use TypeScript.

Answer №1

To summarize in brief: include the following in your tsconfig.json file

"compilerOptions": {
  // lower the emit target ES version to ES2021
  "target": "ES2021",
}

The reason for this change lies in how TypeScript emits class field code. Here is the complete explanation:

When you write TypeScript code like this:

class Greeter {
  greeting: string;
  constructor(message: string) {
    this.greeting = message;
}

it gets transformed into JavaScript code like this:

class Greeter {
  greeting;
  constructor(message) {
    this.greeting = message;
  }
}

The syntax greeting; is part of a recently introduced ES2022 feature known as "class fields declaration."

However, the svelte/compiler internally utilizes acorn as its ECMAScript parser, which has set ecmaVersion: 12 to parse code, corresponding to ES2021.

The responsibility then falls on the svelte-kit team, as they have specified in

"./.svelte-kit/tsconfig.json"
by setting
compilerOptions.target = "esnext"
. This makes TypeScript emit the latest class fields syntax accordingly, as it is valid ES2022 code. Setting "esnext" indicates always keeping up with the latest features.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to troubleshoot the TypeScript error I am encountering in my JavaScript file?

Currently experiencing a TypeScript error within a JavaScript file https://i.sstatic.net/gBzWx.png The issue is within a folder containing only one JavaScript file, and there are no Node.js or package.json files present. I have disabled the TypeScript ex ...

angular 2: how to reset select list values after submission

Issue I am encountering a problem where I am not utilizing a form, but rather using the Model values to populate a select list. Upon clicking the submit button, an API is called with the selected model value. However, after the submission, the select list ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Tips for configuring the global API baseUrl for useFetch in Nuxt 3

Is there a way to globally set the baseUrl used in the useFetch composable, possibly through nuxt.config.ts? How can I prevent having to specify it in each individual useFetch call? ...

Error in Angular compiler-cli: The namespace 'ts' does not contain the exported member 'ResolutionMode'

Currently working on a web application using Angular 16 in Webstorm. The application is still in the pre-release stage, with only minimal functionality completed so far. While editing with ng serve running to test changes as they were made, encountered an ...

What steps should I take to resolve the missing properties error stating '`ReactElement<any, any>` is lacking `isOpen` and `toggle` properties that are required by type `SidebarInterface`?

I've encountered an issue with two React components that appear to be configured similarly. The first component is a Navbar: type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> & { ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Leveraging Firestore Errors within Cloud Functions

Is it possible to utilize the FirestoreError class within Firebase cloud functions? The goal is to raise errors with a FirestoreError type when a document or field is not found in Firestore: throw new FirestoreError(); Upon importing FirestoreError using ...

The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'. signup.component.html &l ...

What could be the reason for TypeScript throwing an error despite having a condition in place?

Having an issue with TypeScript (TS2531) and its non-null type checking. Here's the scenario: if (this.formGroup.get('inseeActivityCode') !== null) { mergedCompanyActivity.inseeActivityCode = this.formGroup.get('inseeActivityCode&ap ...

What could be causing the predefined string error in useState when using TypeScript?

Is it possible to set a predefined string (enum) in React's useState hook? I attempted the following: const [color, setColor] = React.useState<"red | blue">("blue"); however, an error was thrown: Argument of type '& ...

"Discovering issues with the functionality of Antd Table's search and reset capabilities

I'm currently working on integrating search and reset functions in an Antd table. However, I am encountering an issue with the reset (clearAll) function as it does not revert the table back to its initial state when activated. The search functionality ...

What is the reason for TypeScript not providing warnings for unrealistic conditions involving 'typeof' and 'in'?

The recent updates in version 4.9 highlighted the enhanced narrowing with 'in'. Intrigued by this, I decided to experiment with their example in a coding playground. Surprisingly, I discovered that seemingly impossible conditions involving typeof ...

Exploring methods to retrieve the status attribute of an Angular httpClient response

Here is the code snippet that I am working with: this.http.post(url, payload) .subscribe( (req:any)=>{ if(req.status != 200){ console.log('non 200 status'); The this.http in my code refers to a service tha ...

TypeScript will show an error message if it attempts to return a value and instead throws an

Here is the function in question: public getObject(obj:IObjectsCommonJSON): ObjectsCommon { const id = obj.id; this.objectCollector.forEach( object => { if(object.getID() === id){ return object; } }); throw new Erro ...

What is the best way to implement filter functionality for individual columns in an Angular material table using ngFor?

I am using ngFor to populate my column names and corresponding data in Angular. How can I implement a separate filter row for each column in an Angular Material table? This filter row should appear below the header row, which displays the different column ...

Ways to specify a setter for a current object property in JavaScript

Looking to define a setter for an existing object property in JavaScript ES6? Currently, the value is directly assigned as true, but I'm interested in achieving the same using a setter. Here's a snippet of HTML: <form #Form="ngForm" novalida ...

How to Override Global CSS in a Freshly Created Angular Component

My CSS skills are a bit rusty and I need some assistance with a project I'm working on. The project includes multiple global CSS files that have properties defined for different tags, such as .btn. However, these global CSS files are causing conflicts ...

Unable to locate dependencies while testing the react package locally

Recently, I came across this npm package designed for React using Typescript. To debug it locally, I initiated npm link in a new React project but encountered an error: https://i.sstatic.net/nObH6.png I suspect it may not be reading the packages correct ...

Importing Angular Material modules

I've integrated the Angular Material module into my project by updating the material.module.ts file with the following imports: import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MatT ...