I'm trying to pass props into a component in typescript. I've created a LobbyProps
interface and my component has it as an argument. If I try passing the props to LobbyPage
, I get a warning in WebStorm. From what I can tell it is being correctly passed through when I run the application.
TS2322: Type '{ clientSocket: Socket; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. Property 'clientSocket' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
App.tsx (Simplified)
import React, {Component} from 'react';
import {Socket} from "socket.io";
import {LobbyPage, LobbyProps} from "/imports/ui/lobby/LobbyPage";
export class App extends React.Component {
socket: Socket;
constructor(props: Object) {
super(props);
this.state = {};
const io = require("socket.io-client")
this.socket = io.connect("http://localhost:9999/")
}
render() {
return <div>
{/* The warning mentioned above is on the clientSocket variable here*/}
<LobbyPage clientSocket={this.socket}/>
</div>
}
}
LobbyPage.tsx (Simplified)
import React, {Component} from "react";
import {Socket} from "socket.io";
export interface LobbyProps {
clientSocket: Socket
}
export class LobbyPage extends Component {
constructor(lobbyProps: LobbyProps) {
super(lobbyProps);
this.state = {};
}
render() {
return <div>
<h1>Welcome to Meteor!</h1>
<button onClick={() => this.createSession()}>Create Chess Session</button>
</div>
}
private createSession(): void {
this.props.clientSocket.emit("create-session");
console.log("Creating session") // This is successful with no errors during runtime
}
}
From what I can tell this has been done in the same way as the tutorials I've followed.
What is the correct method of passing the props with an interface?
class LobbyPage extends Component<LobbyProps>
? – Arman CharanReact.Component
accepts generic parameters,<P = {}, S = {}, SS = any>
, whereP
is the type ofthis.props
,S
is the type ofthis.state
, andSS
is the type of the snapshot parameter passed tocomponentDidUpdate
. – Arman Charan