首页 > 解决方案 > 错误:模块 '"typescript-declarations"' 没有导出的成员 'ICoordinates'

问题描述

概述: 我正在构建一个 TypeScript 声明 NPM/GitHub 包库 ( https://github.com/jefelewis/typescript-declarations ),我想将其导入到我的项目中,但在导入项目时遇到了问题。

项目:

import { ICoordinates } from 'typescript-declarations';

错误:

Module '"typescript-declarations"' has no exported member 'ICoordinates'.

我试过的:

可能的选项:

src/index.ts

// Imports: TypeScript Types
import * as locationTypes from './types/locationTypes';
import * as measurementTypes from './types/measurementTypes';

// Exports
export {
  locationTypes,
  measurementTypes,
};

src/types/locationTypes.ts:

// Module: Location Types
declare module locationTypes {
  // TypeScript Type: Latitude
  export type TLatitude = number;

  // TypeScript Type: TLongitude
  export type TLongitude = number;

  // TypeScript Type: Coordinates
  export interface ICoordinates {
    latitude: TLatitude;
    longitude: TLongitude;
  }
}

// Exports
export default locationTypes;

src/types/measurementTypes.ts:

// Module: Measurement Types
declare module measurementTypes {
    // TypeScript Type: Measurement (Distance)
    export type TMeasurementDistance = 'Kilometers' | 'Miles' | 'Yards' | 'Feet';

    // TypeScript Type: Measurement (Length)
    export type TMeasurementLength = 'Inches' | 'Feet' | 'Yards' | 'Miles' | 'Light Years' | 'Millimeters' | 'Centimeters' | 'Meters' | 'Kilometers';

    // TypeScript Type: Measurement (Speed)
    export type TMeasurementSpeed = 'Centimeters Per Second' | 'Meters Per Second' | 'Feet Per Second' | 'Miles Per Hour' | 'Kilometers Per Hour' | 'Knots' | 'Mach';

    // TypeScript Type: Measurement (Angle)
    export type TMeasurementAngle = 'Degrees' | 'Radians' | 'Milliradians';
}

// Exports
export default measurementTypes;

标签: typescripttypestypescript-typings

解决方案


您的类型定义以及包构建管道存在一些问题。

  • 您不必cd进入src目录即可运行tsc. 它已经在您的tsconfig哪些文件应该包含在编译中进行了描述。

  • 您的cp命令格式错误。cp需要第二个参数。知道要将源文件复制到的目标文件/目录。虽然我相信你不需要在package.json任何地方复制。根目录中的那个npm很好地描述了您的包裹。虽然如果你有一些我不知道的详细的包发布脚本,那肯定不是真的。

  • declare module someModule类型定义中有不必要的内部模块 ( )。这是 typescript 的一个非常古老的遗留功能,现在已替换为namespaces. 考虑到您尝试导入的方式ICoordinates,我假设您也不需要命名空间。

  • locationTypesexport { locationTypes }您创建另一个名称空间时导出locationTypes您的类型locationTypes.ts现在位于其下。

总而言之,您仍然可以导入ICoordinates为:

import { locationTypes } from 'typescript-declarations'

const coords: locationTypes.default.ICoordinates = null as any

虽然如果您希望导入与以下相同的类型:

import { ICoordinates } from 'typescript-declarations'

您必须对代码进行一些调整:

// --- src/types/locationsTypes.ts
// TypeScript Type: Latitude
export type TLatitude = number;

// TypeScript Type: TLongitude
export type TLongitude = number;

// TypeScript Type: Coordinates
export interface ICoordinates {
  latitude: TLatitude;
  longitude: TLongitude;
}

// --- src/index.ts
// re-export all members of `locationTypes`
export * from './types/locationsTypes'

measurementTypes如果您想在没有显式命名空间的情况下导入它们,情况也是如此。


推荐阅读