简体   繁体   English

这是一个有效的打字稿声明文件吗?

[英]Is this a valid typescript declaration file?

i am trying to import a ReactCrop component from ReactCrop package.我正在尝试从 ReactCrop 包中导入一个 ReactCrop 组件。

it's index.d.ts file is as follows它的 index.d.ts 文件如下

export as namespace ReactCrop;

declare namespace ReactCrop {
  interface Crop {

 } 
  //other interfaces....
}

declare class ReactCrop extends Component<ReactCrop.ReactCropProps> {
   .....
}

export = ReactCrop;

i checked the typescript manual about declaration merging, it says, when merging a class and namespace, the namespace has to export the class.我检查了关于声明合并的打字稿手册,它说,在合并类和命名空间时,命名空间必须导出类。 like below像下面

class Album {
  label: Album.AlbumLabel;
}
namespace Album {
  export class AlbumLabel { }
}

But the ReactCrop type definition, does not export the ReactCrop class.但是 ReactCrop 类型定义,不导出 ReactCrop 类。

So how can i import the Component when the same name "ReactCrop" is an alias for Class and Namespace?那么当同名“ReactCrop”是类和命名空间的别名时,如何导入组件?

Avoid export = ReactCrop;避免export = ReactCrop; . . Instead, I suggest export class ReactCrop {...} .相反,我建议export class ReactCrop {...}

Second thing: you cannot export two items with the same name *.第二件事:您不能导出具有相同名称的两个项目 *. You can export the namespace with the class by:您可以通过以下方式导出带有类的命名空间:

export namespace ReactCrop {
   export class Triangle { }
}
// and 
new ReactCrop.ReactCrop();

Also I suggest that you change the names of one class or namespace to avoid mistakes.另外我建议您更改一个类或命名空间的名称以避免错误。

---Edited--- ---编辑---

  • You can export the namespace and class with the same name in one file.您可以在一个文件中导出具有相同名称的命名空间和类。 TS based on usage will choose correct one. TS 会根据使用情况选择正确的。

There is nothing semantically wrong with this declaration, but it doesn't mean it's valid (meaning it describes what is actually happening in the library).这个声明在语义上没有任何错误,但这并不意味着它是有效的(意味着它描述了库中实际发生的事情)。

In general, namespaces can be used to extend definitions (functions, classes, enums) by adding either just types or executable code inside.通常,命名空间可用于通过在其中添加类型或可执行代码来扩展定义(函数、类、枚举)。 The guide to authoring declaration recommends keeping the exported class within the namespace, but that's a convention, not a technical requirement.创作声明指南建议将导出的类保留在命名空间内,但这是一种约定,而不是技术要求。

In this case, the namespace ReactCrop includes some interfaces like Crop .在这种情况下,命名空间ReactCrop包括一些接口,如Crop This only means you can consume everything this library offers by importing a single exportable.这仅意味着您可以通过导入单个可导出文件来使用该库提供的所有内容。

import ReactCrop from 'whatever';

type Crop = ReactCrop.Crop

<ReactCrop />

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

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