Typescript嵌套类型和接口,以便更好地组织



有没有一种方法可以嵌套类型和接口以更好地组织?

例如。let myshark: Animals.Fish.Shark

为了允许引用嵌套的Shark接口,接口的实现结构是什么?

一次尝试可以是=>

interface Animals{
interface Mamals{
interface Bat {
kind:string;
wings:number;
}
}

interface Fish {

interface Shark {
variant:string;
color:string;
fins:number;
}
}
}

然后按照以下使用它们

let greatwhite: Animals.Fish.Shark;
let mybat: Animals.Mamals.Bat;

我也尝试过使用类和名称空间?有没有合适的方法可以做到这一点,或者不可能获得let myshark: Animals.Fish.Shark之类的类型声明?

如果你不想为每个命名空间使用单独的模块,你可以使用TypeScript特定的namespaces。或者你可以直接定义它们,使Animals在运行时是一个实际的对象,它可以包含属性和类型(你需要记住export任何你想从外部看到的东西(:

namespace Animals {
export namespace Mammals {
export interface Bat {
kind: string;
wings: number;
}
}
export namespace Fish {
export interface Shark {
variant: string;
color: string;
fins: number;
}
}
}

或者,您可以只declare名称空间,然后其中提到的任何内容都会被自动视为导出(因为否则它们就不会被声明(:

declare namespace Animals {
namespace Mammals {
interface Bat {
kind: string;
wings: number;
}
}
namespace Fish {
interface Shark {
variant: string;
color: string;
fins: number;
}
}
}

无论哪种方式,您都可以根据需要通过点符号引用嵌套接口:

let greatwhite: Animals.Fish.Shark; // okay
let mybat: Animals.Mammals.Bat; // okay

游乐场链接到代码

是的,namespace(部分(可以做到这一点,请参阅文档。尽管我怀疑您可能不满意这样一个事实,即不能在不出现错误的情况下将namespace对象嵌套在另一个对象中:
">"declare"修饰符不能在已存在的环境上下文中使用。(1038(";

我个人从来没有这样做过,因为我还没有看到它的好处。

declare namespace GreetingLib {
interface LogOptions {
verbose?: boolean;
}
interface AlertOptions {
modal: boolean;
title?: string;
color?: string;
}
}
// Usage example
const aVariable: GreetingLib.LogOptions = {};
const anotherVariable: GreetingLib.LogOptions = {
verbose: false,
};
const someVariable: GreetingLib.LogOptions["verbose"] = false;

注意:您必须使用某种值来初始化变量。TypeScript不会简单地让您在不提供某种值的情况下启动这些(例如const aVariable: GreetingLib.LogOptions = {};(

在我看来

我更喜欢使用基于某种互属性的扩展类型:
"kingdom": "Plantae" | "Animalia" | ... ,

最新更新