Remi
Remi

Reputation: 5367

How can I use the typings file

I'm working on a React application in conjunction with react-testing-library. In the project I've got a specific function which I would like to check the type on:

const customRender: any = (ui: any, options?: any) =>
  render(ui, { wrapper: AllTheProviders, ...options });

I've found a typings file from Definitely Typed: testing-library__react/index.d.ts

Now I'm reading through the handbook but I can't find how to apply that interface to my function. More specifically the consumption page in the handbook.

I've installed the type file to my project.(package.json, "@types/testing-library__react": "^9.1.2",) and it states that when installing a type, you will just be able to use the project 'with no fuss'.

But how can I make use of the typings so that I can remove the any types in the customRender function?

Can someone point me in the right location?

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

Edit: Almost have it working. However it still seems to have an issue.

interface CustomRenderParams<Q extends Queries> {
  ui: React.ReactElement,
  options?: RenderOptions<Q>
}

const customRender = ({ui, options}: CustomRenderParams): RenderResult =>
  render(ui, { wrapper: AllTheProviders, ...options });

error: TS2314: Generic type 'CustomRenderParams<Q>' requires 1 type argument(s).

Upvotes: 0

Views: 105

Answers (1)

ixrock
ixrock

Reputation: 3864

If you open a file node_modules/@types/testing-library__react/index.d.ts you'll see that render function defined as:

export function render(ui: React.ReactElement, options?: Omit<RenderOptions, 'queries'>): RenderResult;
export function render<Q extends Queries>(ui: React.ReactElement, options: RenderOptions<Q>): RenderResult<Q>;

So you can import and reuse some types from there:

import {render, RenderOptions, Queries} from "@testing-library/react"

function customRender<Q extends Queries>(ui: React.ReactElement, options?: RenderOptions<Q>) {
  return render(ui, { wrapper: AllTheProviders, ...options })
}

Upvotes: 1

Related Questions