0

I'm new to TypeScript and trying to convert a React/Relay project and I'm puzzled by a parsing error on a type import.

This is in an Environment.ts file and it's pretty copied directly from the Relay Todo example.

The Relay example uses Flow and .js extension.

// Environment.ts
import {
  Environment,
  Network,
  RecordSource,
  Store,
  Observable,
  type RequestNode, // Parsing error: ',' expected.
  type Variables,
} from 'relay-runtime';

For reference, here's the fetchQuery that uses the two type imports:

async function fetchQuery(
  operation: RequestNode, // here
  variables: Variables, // and here
): Promise<{}> {
  let headers;
  let token = localStorage.getItem('WUDDIT_JWT');
  if (token) {
    headers = {
      'Content-Type': 'application/json',
      Authorization: token ? `Bearer ${token}` : 'bearer',
    };
  } else {
    headers = {
      'Content-Type': 'application/json',
    };
  }
  return fetch('/graphql', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({
      query: operation.text,
      variables,
    }),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log('ERR', err));
}
1
  • Typescript compiles your code to javascript at the end and removes all types, just import all types and interfaces like another constant and function. Commented Dec 19, 2020 at 8:37

1 Answer 1

1

Typescript has a different syntax for type-only imports:

You can either remove the type:

// Environment.ts
import {
  Environment,
  Network,
  RecordSource,
  Store,
  Observable,
  RequestNode,
  Variables,
} from 'relay-runtime';

Or use import type in a separate import statement:

// Environment.ts
import type {
  RequestNode,
  Variables
} from 'relay-runtime';
// Environment.ts
import {
  Environment,
  Network,
  RecordSource,
  Store,
  Observable
} from 'relay-runtime';

Type only imports are useful for dead code elimination when you need only the types from some module. In this case there isn't much benefit of using type only imports.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.