how to add type declaration to react-typescript project with CRA
Asked Answered
C

2

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?

Creature answered 18/3, 2019 at 22:29 Comment(2)
have you try the following format in your foo.d.ts? 'export function foo() {...};'Effluvium
and what do you mean by that? an implementation for foo? @ChrisChenCreature
T
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;
}
Thumb answered 9/11, 2019 at 11:41 Comment(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?Creature
I
-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;
Intermediary answered 18/3, 2019 at 22:49 Comment(2)
Would love to see some arguments by those who downvoted the answerNitre
@Nitre It's not the TS definition for the foo library.Lois

© 2022 - 2024 — McMap. All rights reserved.