Tips on annotating a SolidJS component with Typescript

I delved into the realm of TypeScript and SolidJS, only to stumble upon this interesting discovery.

https://i.sstatic.net/CGvKm.png

import { Component } from "solid-js"

const Button:Component=({onClick})=>{

    return <button onClick={onClick}>Button</button>
    
}

export default Button

Despite my components being riddled with error highlights, the project runs smoothly, even the functions passed in onClick.

Could this be a misconfiguration in VSCode? I usually code in React.

The file extension is .tsx:

tsconfig.json

{
  "compilerOptions": {
    "strict": true,
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "jsx": "preserve",
    "jsxImportSource": "solid-js",
    "types": ["vite/client"],
    "noEmit": true,
    "isolatedModules": true,
    "paths": {
      "@": ["./src"],
      "@/*": ["./src/*"],
      "$lib":["./src/lib"],
      "$lib/*":["./src/lib/*"]
    }
  }
}

Check out the repository solidjs

Answer №1

The `Component` type from the core module is utilized for marking a SolidJS component. It is parameterized over the `Props` object.

Let's take a look at its definition:

/**
 * A typical `Component` does not come with an implicit `children` prop. If needed, you can define one like so: `Component<{name: String, children: JSX.Element}>`.
 */
export declare type Component<P = {}> = (props: P) => JSX.Element;

Considering that your component only has one prop, `onClick`, which expects a click event as its argument of type `MouseEvent`:

import { Component } from "solid-js"

interface ButtonProps {
  onClick: (event: MouseEvent) => void
}

const Button: Component<ButtonProps> =({ onClick })=>{
  return (
    <button onClick={onClick}>Button</button>
  );
}

export default Button;

All my components show errors underlines, but the project functions correctly, including the onClick callbacks.

Typescript serves as a helpful tool, ensuring that components operate smoothly once compiled into error-free JavaScript code.

If you don't specify a particular prop type for `Component`, the props will default to a plain object because it is set to `P = {}` by default.

The reason for the error is that your Button Component anticipates an empty object `{}` as its prop, yet you are supplying `{ onClick: (event: MouseEvent) => void }`.

Could this be a vscode misconfiguration? I usually code in React without issues.

It is unlikely related to vscode since it natively supports typescript, eliminating the need for additional extensions if typescript is included in your `package.json` and configured with a `tsconfig.json` file.

The typing structure of a Solid component differs from that of React. In Solid, all components are essentially function components without passing state down to their children, hence why there is no equivalent of `S = {}` in the `Component` type of Solid.

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

In JavaScript, loop through an array of arrays and combine them using the concat

If I have an array like [["a", "b"], ["c", "d"]], is there a way to iterate, reduce, map, or join this array in order to get the desired output of ["ac", "ad", "bc", "bd"]? What if the array is structured as [["a", "b"], ["c", "d"], ["e", "f"]]; how can we ...

What is the reason behind the occurrence of `(User & { _id: Schema.Types.ObjectId; }) | null` when calling findById?

Today marks my debut using typescript and mongoose. Here's a glimpse of what I've worked on. Type export interface User extends Document { _id: ObjectId; lastName: string; } Schema const userSchema = new Schema<User>({ lastName: { t ...

Disabling the ripple effect on the primary action in React Material lists: A Step-by-Step

I was attempting to include two action buttons at the opposite ends of a list component. https://i.stack.imgur.com/juv8F.gif When clicking on the secondary action (delete icon on the right), the ripple effect is confined to just the icon. On the othe ...

Interacting with a JavaScript alert by clicking the OK button using C# in a web browser control

In my C# Windows Forms program, I am utilizing a webbrowser control to navigate multiple pages of a website and interact with forms to carry out transactions. I initially tried using httpwebrequest and webclient, but encountered challenges with cookies and ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Leveraging external variables within JavaScript

In my views.py, I used to have the following structure: ... if mymodel.name == 'Myname1': #do something elif mymodel.name == 'Myname2': #do something else ... However, I found this method cumbersome because if the names change ...

I am utilizing the useEffect hook along with Axios to fetch data from the backend. My goal is to retrieve two arrays of objects in order to render them on the

I am attempting to retrieve 2 arrays of objects from my MySQL database using Axios, but the console.log output '3' is showing an empty array. I'm not sure what's causing this issue. export default function Editar() { let {clienteId} = ...

Keeping state between navigations in Ionic and AngularJS: A guide

In the process of developing my very first hybrid mobile application using Ionic and AngularJS, I have encountered a challenge that I am currently trying to resolve. The issue at hand involves maintaining the state of the graphical user interface between n ...

Solving the issue of redirecting with while-else loop in Express.js

app.post('/process', function(request, response){ var i = 0; while(i < data.length){ if(data[i].condition1 == condition1 && data[i].condition2 == condition2){ response.redirect('/first_page'); ...

Encountering issues with posting data on a straightforward Node.js form using routes

I'm having trouble getting a simple form to post within my NodeJS/ExpressJS app. The code in my app.js file (referred to as server.js) is as follows: var express = require('express'); var fs = require('fs'); var path = require(&a ...

Is there a way for me to determine when AJAX-loaded content has completely loaded all of its images?

After making an AJAX request to load HTML, it includes img tags within it. I am in need of a way to detect when these images have finished loading so that I can adjust the container size accordingly. Since I do not know how many images will be present in ...

Click to load an IFRAME upon clicking

I am encountering an issue with IFRAMEs loading onClick. The problem lies in the script provided below which always loads the content of the first iframe, whereas my expectation is to load only the iframe corresponding to the link clicked. $('.toggle ...

In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line? if (!user) { const error = new Error('Invalid user.') error.data = someObject error.code = 401 throw error } Here's an example (with data and code properties populated) if (!user) th ...

Verify whether the user has reached the bottom of the iframe while scrolling

I currently have a simple iframe placed in the center of my webpage. The code for the iframe is as follows: <iframe class="iframe" src="http://route-to.page"></iframe> As the user scrolls down to reach this iframe, it will be assigned an addi ...

The index.js file in ReactJs is failing to run completely

A couple of months back, I delved into the world of React but eventually put it on hold. Today, I decided to pick it back up and took the following steps: npm init npm install npm start Everything seemed to run smoothly (No Errors), but strangely nothing ...

Clone all documents from a NodeJS mongoose collection and transfer them to a different server's database

I need assistance with migrating my database to a new server. My collection consists of approximately 410,000 documents, and I am looking to transfer them in batches of 100 to my new server that runs on mongodb. Below is the code I have written for this ...

Utilize static members of an imported type within an Aurelia view

Currently, I am utilizing Aurelia in combination with TypeScript. In my code, I have defined a simple type with static variables as shown below: export class MyModule { static foo = false; } Furthermore, I have created an Aurelia view model as follo ...

What is the best way to set the length of an undefined item in an object to 0 in reactjs?

I am facing a challenge keeping track of scores within each article and displaying them accurately. The issue arises when there is a missing "up" or "down" item in the object. Below is the data containing all the votes: const votes = { "1": { "up": ...

Having trouble retrieving data from the server for the POST request

I am fairly new to using Jquery and Ajax requests. I'm currently working on a website where I have a simple form that collects an email address from users and sends it to the server. However, I'm struggling to figure out how to capture the form d ...

Tips for encoding AngularJS ng-model in real-time

Recently, I embarked on a new project and wanted to incorporate some AngularJS magic. The only obstacle is my limited expertise in AngularJS or JavaScript, making it difficult for me to figure out how to make it work. One key requirement is that the functi ...