Inquiry regarding the TS2322 error encountered in a Svelte Component

I'm currently exploring Svelte using TypeScript.

I encountered a TS23 error while working on this piece of code.

<script lang="ts">
    import ComponentA from './ComponentA.svelte';
    import ComponentB from './ComponentB.svelte';

    let components = [
        { name: 'ComponentA', component: ComponentA },
        { name: 'ComponentB', component: ComponentB }
    ];
    let selected;
</script>

{#each components as { name, component } (name)}
    <label><input type="radio" value={component} bind:group={selected} />{name}</label>
{/each}

<svelte:component this={selected} />

Type 'typeof ComponentA__SvelteComponent_' is not assignable to type 'string | number | string[]'.

Type 'typeof ComponentA__SvelteComponent_' is missing the following properties from type 'string[]': pop, push, concat, join, and 28 more. ts(2322)

The error is related to the value attribute within the input tag.

Any suggestions on how to tackle this issue? I'm a bit lost here.

Answer №1

When working with Typescript, it is important to remember that the value attribute of a radio input can only be either a string, number, or an array of strings (string | number | string[]). If you anticipate unique values for the inputs, you can utilize the name attribute as the value instead. While this approach may require some additional effort to map the name back to a component, the extra work involved is relatively minor.

In the provided example, the radio inputs are bound to the variable selectedName instead. Additionally, a reactive statement is established to identify the corresponding component whenever there is a change in the value of selectedName.

<script lang="ts">
    import Test1 from './Test1.svelte';
    import Test2 from './Test2.svelte';

    let components = [
        { name: 'Test1', component: Test1 },
        { name: 'Test2', component: Test2 }
    ];
    let selectedName;

    $: selected = components.find((c) => c.name === selectedName);
</script>

{selectedName}
{#each components as { name, component } (name)}
    <label
        ><input type="radio" value={name} bind:group={selectedName} />{name}</label
    >
{/each}

{#if selected}
    <svelte:component this={selected.component} />
{/if}

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

Using res.locals with TypeScript in Next.js and Express

In my express - next.js application, I am transferring some configuration from the server to the client using res.locals. My project is written in typescript and I am utilizing "@types/next": "^8.0.6". The issue at hand: typescript is throwing an error st ...

Error message: Typescript class unable to access methods because of undefined properties (TypeError: Cannot read properties of undefined (reading 'method_name'))

During the compilation process, everything goes smoothly with no errors. However, when I try to call the method in the controller, an error occurs. It seems that some class methods are missing during the compilation phase. If you require more information ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

Perplexed by the implementation of "require(...)" in TypeScript

After reading several blog posts, my understanding of TypeScript modules remains confusing. I have worked with three different modules (all installed via npm) and encountered varying behavior: (1) Importing and using Angular 2 from npm required me to add ...

The functionality of Angular/Typescript class.name appears to fail during a production build

Using Angular 5, I encountered an unusual problem with the class.name property. We have a TypeScript function as shown below: export class ApiService { public list<T>(c: new(values: Object)=> T) { var cname = c.name; .... } } When ...

The AngularJS Service fails to properly convert incoming Json Responses into Model objects during piping

I have been studying AngularJS 17 and recently developed a login application. However, I am facing an issue where the server response is not being properly mapped to the object in the Model Class. Response: { "id": 1, "userName& ...

My component is missing the ChangeDetectorRef in Nativescript

I am attempting to automatically update an array within a Listview by utilizing ChangeDetectorRef in the following way: import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef } from "@angular/core"; @Component({ selector: "regi ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Obtaining Input Field Value in Angular Using Code

How can I pass input values to a function in order to trigger an alert? Check out the HTML code below: <div class="container p-5 "> <input #titleInput *ngIf="isClicked" type="text" class="col-4"><br& ...

In Typescript, you can easily group a string into sections that consist of digits like 345-67, along with text containing a

I have a string that looks like this: "[111-11] text here with digits 111, [222-22-22]; 333-33 text here" and I am trying to parse it so that I can extract the code [111-11], [222-22-22], [333-33] along with their respective text descriptions. The challeng ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...

Working with intricately structured objects using TypeScript

Trying to utilize VS Code for assistance when typing an object with predefined types. An example of a dish object could be: { "id": "dish01", "title": "SALMON CRUNCH", "price": 120, ...

Enhancing JSON data: Transforming basic JSON structure into more complex format

I am currently working on a typescript file that is receiving a JSON response from an external API. I am in need of assistance to convert the received JSON into a different format. Could someone please help me with this JSON conversion task? Sample JSON d ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

Using TypeScript to set an HTMLElement in a web page

Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings. I had a function that calculated the total offset needed ...

Typescript inheritance results in an undefined value being returned

I am trying to understand the code below, as I am confused about its functionality. In languages like C# or Java, using the base or super keyword usually returns values, whereas in TypeScript, I am receiving "undefined". However, when I switch from using " ...

The function encounters an undefined array when called, despite the array being defined outside of the

Encountering an issue where an array I initiate is suddenly undefined within a function. Here is the code snippet: import { Component, OnInit } from '@angular/core'; import { text } from '@angular/core/src/render3'; import{SheetModel} ...

What is the method for obtaining a literal type through a function parameter to use as a computed property name?

Can you help me with this code snippet? const fn = (name: string) => { return { [name]: "some txt" }; }; const res = fn("books"); // books or any other string The type of res recognized by TS is: const res: { [x: string]: string ...

Angular class requires multiple class members and validators for MatSelection List to be bound with Formbuilder

Could you please guide me on how to connect the Google Angular Materials mat-selection-list with the FormBuilder? We have the following class and are attempting to utilize Reactive Form Builder for this purpose. While we are aware of how to link data class ...