如何将命名空间类型声明拆分为多个文件,同时能够在 Typescript 中作为单个命名空间导入



我正在尝试实现以下目标:(没关系,这些类型的结构相同。这仅用于演示目的(。目标是为我要导出的命名空间没有一个大文件。

import Animal from 'types/animal/index.ts'
const dog:Animal.Dog = {
  sound: 'bark',
  legs: 4
}
const cat:Animal.Cat = {
  sound: 'meow',
  legs: 4
}

类型/动物/索引.ts

// somehow import the animal types from separate files and export in one "Animal" namespace

类型/猫

export namespace Animal {
  export interface Cat {
    sound: string
    legs: number
  }
}

类型/狗.ts

export namespace Animal {
  export interface Dog {
    sound: string
    legs: number
  }
}

假设你的Dog.tsCat.ts确实驻留在types,而不是types/animal,像这样的东西在types/animal/index.ts应该可以完成这项工作:

import * as Animal_Dog from '../Dog';
import * as Animal_Cat from '../Cat';

namespace Animal {
    export type Dog = Animal_Dog.Animal.Dog;
    export type Cat = Animal_Cat.Animal.Cat;
}
export default Animal;

最新更新