9

I have created a react typescript project with CRA with the command yarn create react-app my-app --typescript

now I have a module foo installed that does not have any typing not by default, not in defentlytyped repository.

i.e. in a component, I have

import {bar} from 'foo';

which throws error Type error: Could not find a declaration file for module 'foo'. '/*/node_modules/foo/dist/entry.js' implicitly has an 'any' type.

I created foo.d.ts in types folder at the root of the project like

declare module 'foo'{ import * as React from 'react' }

just to have the foo as type any but still, get the same error. it seems that whatever compiler (webpack,other transpiler) does not find the declaration at types folder

how can I add custom type declaration to the project?

Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123

2 Answers2

1

Here is a real use-case example. I managed to integrate kendo-ui-core into CRA+Typescript.

The problem was that there are no typings for kendo-ui-core, namely the typings have a different name: @types/kendo-ui

Typescript was complaining about not having type definitions

VS Code complaining about missing declaration

To resolve the issue, create a file called kendo-ui-core.d.ts in your /src directory with the following contents:

// src/kendo-ui-core.d.ts
declare module 'kendo-ui-core' {
  import * as KendoTypings from '@types/kendo-ui';
  export = KendoTypings;
}
Tudor Morar
  • 3,720
  • 2
  • 27
  • 25
  • 1
    do we need to add the `kendo-ui-core.d.ts` in a specific folder like `src/@types` and then add that folder to `tsconfig`? – Amir-Mousavi Mar 19 '20 at 18:18
-2

This works:

/* create src/CustomTypes.ts */

namespace MyCustomType {
  export type foo = number;
}

export default MyCustomType;

use like this:

import MyCustomType from "src/CustomTypes";

const num: MyCustomType.foo = 123;
Tyro Hunter
  • 755
  • 1
  • 8
  • 20