Remi
Remi

Reputation: 5367

Writing simple test in Typescript gives type assertion error

Using typescript to define a test outputs Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead. error.

./app.test.ts

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div); // here the error is produced
});

How should the component be defined in Typescript?

Example code from CRA Facebook page


edit: Accepted answer by @rzelek pointed in the right direction.

As defined in the JSX handbook the compiler options define the way your JSX is interpreted. In my case used "jsx": "react" so that means the method React.createElement() needs to be used in order to create a component (see table in JSX handbook):

final result: ./app.test.ts

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const app = React.createElement(App);
  const div = document.createElement('div');
  ReactDOM.render(app, div);
});

Upvotes: 1

Views: 2008

Answers (2)

rzelek
rzelek

Reputation: 4013

Typescript files that contain JSX should have *.tsx extension instead of .ts.

You can see similar issue here: https://github.com/palantir/tslint-react/issues/141

Additionally, your tsconfig.json should have appropriate config. For my CRA apps, this is:

{
  "compilerOptions": {
    ...
    "jsx": "preserve",
    ...
  }
}

https://www.typescriptlang.org/docs/handbook/jsx.html

The error you can see most probably comes from tslint, not Typescript itself. You can see a rule here: https://palantir.github.io/tslint/rules/no-angle-bracket-type-assertion/. Basic tslint config for CRA should be something similar to this:

{
  "extends": ["tslint:latest", "tslint-react"],
  "rules": {
    // override tslint-react rules here
    "jsx-wrap-multiline": false
  }
}

As a good starting point, you can try adding "no-angle-bracket-type-assertion": false to tslint.json rules and see if error disappears.

PS. tslint usually points you to source of the error, for example: ERROR: app/components/Root/index.ts[6, 7]: Type assertion using the '<>' syntax is forbidden. Use the 'as' syntax instead.

Upvotes: 1

yuval.bl
yuval.bl

Reputation: 5074

How's your <App> component defined?

Let's assume these are the component props and state interfaces (I usually define them in the beginning of a file for each component):

interface Props {
   //... some props
}
interface State {
   //... some state
}

A class component can be defined like this

class MyComponent extends React.Component<Props, State> { ... }

A function component can be defined like this

const MyComponent: React.FC<Props> = ...

You might want to check react-redux-typescript-guide

Also, this question might be related

Upvotes: 0

Related Questions