简体   繁体   English

如何使用 CRA 向 react-typescript 项目添加类型声明

[英]how to add type declaration to react-typescript project with CRA

I have created a react typescript project with CRA with the command yarn create react-app my-app --typescript我使用命令yarn create react-app my-app --typescript创建了一个带有 CRA 的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.现在我安装了一个模块foo ,它默认没有任何类型,不在 defentlytyped 存储库中。

ie 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.抛出错误Type error: Could not find a declaration file for module 'foo'. '/*/node_modules/foo/dist/entry.js' implicitly has an 'any' type. 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我在项目根目录下的 types 文件夹中创建了foo.d.ts

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

just to have the foo as type any but still, get the same error.只是为了将foo设为any类型,但仍然会得到相同的错误。 it seems that whatever compiler (webpack,other transpiler) does not find the declaration at types folder似乎无论编译器(webpack,其他转译器)都没有在types文件夹中找到声明

how can I add custom type declaration to the project?如何向项目添加自定义类型声明?

Here is a real use-case example.这是一个真实的用例示例。 I managed to integrate kendo-ui-core into CRA+Typescript.我设法将 kendo -ui-core集成到 CRA+Typescript 中。

The problem was that there are no typings for kendo-ui-core, namely the typings have a different name: @types/kendo-ui问题是 kendo-ui-core 没有类型,即类型具有不同的名称: @types/kendo-ui

Typescript was complaining about not having type definitions打字稿抱怨没有类型定义

VS Code 抱怨缺少声明

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 的文件,其中包含以下内容:

// src/kendo-ui-core.d.ts
declare module 'kendo-ui-core' {
  import * as KendoTypings from '@types/kendo-ui';
  export = KendoTypings;
}

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM