Reputation: 2949
I am trying to Hello World React with Typescript. I wrote the code below. This code works when I use method 1, but throws error on method 2
Method 1
- TypeScriptComponent.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import Button from 'react-bootstrap/lib/Button'
interface TypeScriptComponentProps {
}
function handleClick() {
console.log("Hello World")
}
export const TypeScriptComponent = (props: TypeScriptComponentProps) => <Button onclick={handleClick()} bsClass="glyphicon glyphicon-new-window"></Button>;
This code works (with a bit unexpected behaviour with handleClick function, which I can resolve later.)
But this method wont work
Method 2
- TypeScriptComponent.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import Button from 'react-bootstrap/lib/Button'
interface TypeScriptComponentProps {
}
function handleClick() {
console.log("Hello World")
}
export default class TypeScriptComponent extends React.Component<TypeScriptComponentProps, {}> {
render() {
return (<Button onclick={handleClick()} bsClass="glyphicon glyphicon-new-window"></Button>)
}
}
Method 2 throws error
ERROR in [at-loader] ./components/TypeScriptComponent.tsx:43:70 TS2339: Property '_ proto _' does not exist on type '() => any'.
ERROR in [at-loader] ./components/TypeScriptComponent.tsx:46:5 TS2346: Supplied parameters do not match any signature of call target.
I am not able to figure out what is the difference between the two methods? Why those errors??
Upvotes: 6
Views: 6205
Reputation: 16856
Your code has multiple issues.
* as React from 'react'
. Same for ReactDOM.Button
TypeScript can not find anything there.onclick
prop on Button
. Only an onClick
.onClick
doesn't make any sense. You have to pass the function not the return value of the function.Here is what works for me:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Button } from 'react-bootstrap';
interface TypeScriptComponentProps {
}
function handleClick() {
console.log('Hello World');
}
class App extends React.Component<TypeScriptComponentProps, {}> {
render() {
return (<Button onClick={handleClick} bsClass="glyphicon glyphicon-new-window">Click Me!</Button>)
}
}
ReactDOM.render(
<App />,
document.getElementById('root') as HTMLElement
);
My config is using ts-loader
not at-loader
. Did you add the CheckPlugin
to your webpack config? Otherwhise you will not get any type errors.
If you're new or unfamiliar with Webpack/TypeScript/React-combo, I would suggest checking out this fork of create-react-app
: https://github.com/wmonk/create-react-app-typescript :)
Upvotes: 4