Pass props to child component in React, with Typescript (TSX file)

Simon picture Simon · Sep 22, 2016 · Viewed 9.4k times · Source

I am using VS2013 and getting an existing project set up to use React (0.14) and Typescript (1.8.5). My React code works fine as JSX file. I have one error in my new TSX file that I can't figure out.

I have 30 odd errors on every prop pasted to a component down the tree - these all read:

Property 'nameOfProp' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes> & {} & { children?: Reac...'.

Here is an example code that gets TypeScript upset. Any help would be greatly appreciated as this is the one of the last hurdles to get up and running with React in production. NOTE: I have not included information about the App state to save space, but the red lines are only on the child component names (filter, name, id, count)

Answer

Nitzan Tomer picture Nitzan Tomer · Sep 22, 2016

The signature for React.createClass is:

function createClass<P, S>(spec: ComponentSpec<P, S>): ClassicComponentClass<P>;

The generic P and S define the props and state.
The compiler doesn't know what are the types for those and so it uses the base which is the type you get in your error.

You can do:

interface AppState {
    filter: string;
    count: number;
    id: string;
    name: string;
}
var App = React.createClass<{}, AppState>(...);

interface FilterItemProps {
    count: number;
    name: string;
}
var FilterItem = React.createClass<FilterItemProps, {}>(...);

If you're using classes:

class App extends React.Component<{}, AppState> {
    render() {
        ...
    }
}