将类型从声明文件导出到外部项目的最佳实践

Best practice for exporting types from declaration file to external project

我有一个可行的解决方案 - 导出声明文件中定义的类型,这些类型可以在我的项目中使用,也可以导出到外部项目。

我能做到这一点的唯一方法是使用命名空间来包装类型。

github - 项目 X

@types/index.d.ts

declare namespace projectGlobal {
  interface Person = {
    name: string;
    age: number;
  }
}
// other localised types here, cannot be exported...
interface Local {
  func: () => string
}

src/index.ts

export type Person = ProjectGlobal.Person; // can only export if referenced via namespace.
// export type Local = Local; // This fails to export

const person1: Person = {
  name: 'john',
  age: 45
}

github 项目 Y

import {Person} from 'projectx';

const person1: Person = {
  name: 'john',
  age: 45
}

虽然我很乐意接受这个解决方案,但我想知道这是否是正确的方法,或者是否有最佳实践。

不应该那样使用声明文件。实际上,通常你根本不写它们。你想写它们的主要原因是:

  1. 当您在 JavaScript 中有一个库并且您希望 TypeScript 用户也能够使用它。你可以用 TypeScript 重写你的库,但这并不好玩,所以你可以只写声明并将代码留在 JavaScript.

  2. 有时候如果你想声明一些全局的东西。例如,在 React 项目中,您可以从图像文件 .png.jpg 和 co 导入数据。所以 React 创建了一个 .d.ts 文件,其中包含它们的声明(因为默认情况下 TS 不认为这些文件是模块):

declare module '*.jpg' {
  const url: string
  export default url
}

差不多就这些了,在其他情况下只需使用普通的 .ts 文件:

export type Person = {
  name: string
  age: number
}

const person1: Person = {
  // ...
}

我看不出有任何理由,为什么你不能这样做,如果你有,请随时发表评论。如果你只是想要类型和逻辑之间的分离,创建 types.tsdo-stuff.ts 并且只使用 index.ts 来重新导出东西:

// types.ts
export type Person = {
  name: string
  age: number
}
// do-stuff.ts
import { Person } from './types'

const person1: Person = {
  // ...
}
export default person1
// index.ts
export * from './types'
export { default } from './do-stuff'
// you can write this line just in case you will want to export something
// with a named export
export * from './do-stuff'