How can dynamic attributes of any type be assigned to a nested component in Svelte?

When working with a Svelte component that has dynamic attributes which are not strings (such as a number and an array), like in the example of MySimpleComponent.svelte:

<script lang="ts">
    export let index : number;
    export let paragraphs: string[];
</script>

<h3> { index } </h3>
{#each paragraphs as paragraph, i}
    <p> { paragraph } </p>  
{/each}

How can this component be used within another component and specify those attributes inline? Attempting the following code results in an error:

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

<MySimpleComponent
    index = { 1 },
    paragraphs = {[
        'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
        'Aut vel quia vel ducimus eius perferendis.' 
    ]},
/>

The error message reads TS 2322:

Type 'string' is not assignable to type 'number'
(or to type string[]). It seems the { } syntax is assuming a string value inside, converting { 1 } to '1' instead of preserving it as a number.

What would be the correct approach to handle this scenario? Thank you.

Answer №1

The issue at hand pertains to commas, as props are only separated by whitespace:

<MySimpleComponent
    index={1}
    paragraphs={[
        'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
        'Aut vel quia vel ducimus eius perferendis.' 
    ]} />

(The presence of whitespace in and around the braces, along with adjacent to the = sign, is inconsequential.)

Curly brackets pass values exactly as they appear without undergoing any alterations. To pass strings, one would encapsulate the values with quotes alongside additional text or manually invoke .toString() (for instance, index="1").

It should be noted that if a property exclusively consists of a {...} expression, it will not be transformed into a string but once again passed unchanged (refer to this issue for demonstrations).

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

Simultaneously activate the top and bottom stacked components by clicking on them

One of my components has two child components, A and B. Component A is set to position: absolute and placed on top of component B like an overlay. Additionally, component A has a higher z-index. Both components have onClick events attached to them. My que ...

After the installation of Windows 10 and the latest version of NodeJS, Gatsby seems to be

The gatsby project I set up following the official website instructions seems to be malfunctioning. NodeJS version: v16.15.0, npm version: 8.8.0, gatsby version: 4.13.0, gatsby CLI version: 4.13.0 C:\Users\Dell\Desktop\New folder&bsol ...

Using Node.js to Send Parameters in a POST Request

I have a node.js application with an express framework and a POST route defined as follows: app.post('/test', function(req, res){ //res.send(req.body.title + req.body.body) console.log(req.params); console.log(req.body); console.log(req.bod ...

Master the art of animating ng-view transitions with AngularJS

I have 2 distinct HTML pages, namely welcome.html and login.html. These two pages are incorporated or "inserted" into a common page called index.html through the utilization of an exclusive attribute known as ngview, together with a router provider. This i ...

Executing multiple queries in a node.js transaction with Sequelize using an array

I am looking to include the updates on the clothingModel inside a transaction, with the condition that if it successfully commits, then update the reservationModel. This is the snippet of code I am attempting to refactor using sequelize.transaction tr ...

Initiate asynchronous function

After making my action asynchronous, I encountered a problem where the dispatch is not working as expected. Every time I dispatch the action, it seems to immediately enter the catch block with the value of false. Here is the section of code from my page wh ...

What is the best way to switch content between tabs using ajax and php?

I have organized my content into two tabs and I am switching between the tabs using JavaScript. <div class='tab-container'> <div class='tab-1'> <?php $sql="SELECT * FROM posts WHERE status='tab1'"; echo "<d ...

Tips for specifically targeting the clicked table row using angularJS directives ng-show and ng-hide

Seeking assistance with implementing a toggle function in an angularJS app for showing/hiding a specific table data section. Currently, the toggling functionality is working, but it toggles every row in the table instead of just the clicked row. See this e ...

Is there a way to find the minimum and maximum intervals based on a consecutive property in a JavaScript Object?

Seeking assistance in calculating the maximum and minimum date differences (in hours or float days) for each location. When there is only one date interval for a location, consider the difference from the date above it. The data is already sorted by date ( ...

What is the best way to eliminate a specific item from an array of objects within a function?

1. When utilizing the findUnsubmitted function with an array of submission objects, a specified date, and student names array, the function returns the names of students who have not completed any quiz on that particular date. If the findUnsubmitted featu ...

When the button is clicked, the image vanishes into thin

One common issue is the image disappearing when users click on the Rotate Anti-clockwise or Rotate Clockwise buttons. This can be a frustrating problem to tackle! Check out this link for more information. If you run into this issue, here are some tips: ...

Nodejs functions properly on a local machine, however, it encounters issues when deployed on a VPS

My nodejs/javascript code seems to be running fine on my local pc, but when I try to run it on my vps, it's not working properly. Even though I have the same node_modules installed and the code is identical. Here's a snippet of my code for refere ...

Exploring the World of Infinite Scrolling with React.js and Material_ui

I am currently working on a project using react.js As part of this project, I need to implement a board with infinite scroll similar to Facebook I have a specific question regarding this implementation. When scrolling the board and loading more posts li ...

Node.js appears to experience delays following successful connection to local MongoDB

I am encountering a problem while attempting to establish a connection to my MongoDB database and fetch data from it. After the connection is established, the terminal freezes, forcing me to interrupt the process using ctrl+C. Below is the code I am worki ...

Typescript: Select just one option from the union

There is a specific Query type that contains the getBankAccounts property: export type Query = { getBankAccounts: GetBankAccountsResponseOrUserInputRequest, }; This property can return either a GetAccountsResponse or a UserInputRequest: export type Ge ...

Looking to adjust the HSL of individual colors on a JavaScript canvas, similar to editing in Photoshop?

I'm looking to manipulate the HSL of an image using Javascript. I don't want to apply changes to the entire image at once, but rather target specific color sets like blues and yellows, similar to how it's done in Photoshop. What type of da ...

Is employing the HTML 'confirm' method considered a best practice?

How can I alert a user before they discard changes in a form while switching to another page? Is using if (!confirm("Are you sure")) return false;... considered a good practice for this type of message? Or should I consider using a modal panel instead? (W ...

What is the reason behind IE7 and IE8 claiming to have 'hasLayout' when in reality it does not possess such a feature?

HTML: <div class="table" > <div class="row" > <span>Table with DIV</span> <span>column2</span> <span>column3</span> </div> <div class="row" > <span>col ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

Is there an Angular @input attribute that concludes with an exclamation mark?

This source code showcases the usage of @Input properties with an exclamation mark (!) at the end. An example is shown below: @Input() token!: StripeToken The presence of ! in this case signifies a non-null assertion operator, but what is the significanc ...