Samuel Colvin
Samuel Colvin

Reputation: 13349

Typescript types for Solid-js components

How do I convert the first example from the Solid-JS documentation to be valid typescript?

import { render } from "solid-js/web"

const HelloMessage = props => <div>Hello {props.name}</div>

render(() => <HelloMessage name="Taylor" />, document.getElementById("hello-example"))

I'm getting an error about props having no type hint, specifically Parameter 'props' implicitly has an 'any' type.

With react I would use React.FC, but I can't find the equivalent with Solid-JS.

Upvotes: 8

Views: 6657

Answers (2)

Samuel Colvin
Samuel Colvin

Reputation: 13349

I found the solution, is using the Component generic:

import {render} from 'solid-js/web'
import {Component} from 'solid-js'

const HelloMessage: Component<{name: string}> = (props) => <div>Hello {props.name}</div>

render(() => <HelloMessage name="Taylor" />, document.getElementById("hello-example"))

Upvotes: 10

Natasha
Natasha

Reputation: 816

An alternative could be the following (without having to import type Component):

» Demo

import {render} from 'solid-js/web'

function HelloMessage(props: {
  name: string
}) {
  return (
    <div>
      Hello {props.name}
    </div>
  )
}

render(() => <HelloMessage name="Taylor" />, document.getElementById('app'))

Or if you prefer:

const HelloMessage = (props: { name: string }) =>
  <div>Hello {props.name}</div> 

BTW: In your question you are using Hello {props.name} which is fine as props is a reactive object and the expression props.name is also reactive ... in your answer you are using Hello {name} instead, which will never update, as name is just a string which is by nature constant and therefore none-reactive.

Upvotes: 5

Related Questions