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

I would like to write a new web application in React that uses Relay to communicate with the GraphQL server . JSX support for TypeScript has recently been added . But there is no type declaration file (.d.ts) for Relay on DefinitelyTyped . How to write my application in TypeScript without having to write a typed file for Relay?

+4
source share
1 answer

Typescript does not require typing for all the libraries you use, it is highly recommended. Use relay without typing:

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 Helloas a normal relay component. The idea is that require- this is a function that takes a string and returns any, so you can use the variable Relayin the same way as in vanilla Javascript.

If you are not using Node.JS characters, you may need to add text for require. Somewhere in your d.ts files add:

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

declare var require: NodeRequireFunction;
+3
source

Source: https://habr.com/ru/post/1618930/


All Articles