Korneel
Korneel

Reputation: 1507

How to use Facebook Relay in a React app written in TypeScript (TSX)?

I would like to write a new web application in React that uses Relay to communicate with a GraphQL server. Recently JSX support was introduced for TypeScript. But there is no typings declaration file (.d.ts) for Relay on DefinitelyTyped. How can I write my application in TypeScript without having to write a typings file for Relay first?

Upvotes: 4

Views: 2117

Answers (1)

Gunchars
Gunchars

Reputation: 11076

Typescript doesn't require you have typings for all the libraries you use, it's just highly recommended. To use Relay without typings:

import * as React from "react"
let Relay = require("react-relay")

interface HelloProps extends React.Props<HelloComponent> {
  viewer: {
    message: string
  }
}

class HelloComponent extends React.Component<HelloProps,void> {
  render() {
    return <div>Hello { this.props.viewer.message }</div>
  }
}

let Hello = Relay.createContainer(HelloComponent, {
  fragments: {
    viewer: () => Relay.QL`fragment on Viewer { message }`
  }
})

Then use Hello as a regular Relay component. The idea is that require is a function that takes a string and returns any so you can then use Relay variable as you would in vanilla Javascript.

If you're not using Node.JS typings, you might need to add a typing for require. Somewhere in your d.ts files, add:

interface NodeRequireFunction {
  (id: string): any;
}

declare var require: NodeRequireFunction;

Upvotes: 3

Related Questions