打字稿'tree'对象定义



我不太确定我正在创建的对象类型的"名称"。我称它为树,因为它看起来类似于没有关系的嵌套树。本质上我想要一个具有嵌套定义的对象,如下所示

{
test1: OptionsInterface,
test2: {
test3: OptionsInterface,
test4: {
test5: OptionsInterface,
},
},
}

所以第一级可以是OptionsInterface的,也可以是{[s: string]: OptionsInterface}有没有办法在对象的每个"级别"上使用它?

我尝试像这样定义上述内容:

export default class ApiClient {
constructor(options: {[s: string]: OptionsInterface | {[s: string]: OptionsInterface}}) {}

但这只会是 2 深吧?有没有办法定义我的示例对象而无需手动添加每个深度?

用例

我希望能够这样称呼我的班级

api = new ApiClient(routeSchema);
await api.call('test2.test4.test5', params);

通话中:

async call(config: string, variables: object = {}): Promise<Response> {
const options = get(this.configuration, config);
if (options === undefined) {
throw new ConfigNotDefinedExpection(config);
}
return await this.callWithOptions(options, variables);
}

callWithOptions期望OptionsInterface的地方

当然,你可以这样做。

type NestableOptionsInterface = OptionsInterface | { [k: string]: NestableOptionsInterface }

也就是说,NestableOptionsInterface要么是OptionsInterface,要么是字典,其键是您想要的任何内容,并且其值NestedOptionsInterface。 所以这是一个递归定义。 让我们测试一下:

class Foo {
constructor(options: NestableOptionsInterface) { }
}
declare const optionsInterface: OptionsInterface;
new Foo(optionsInterface); // okay
new Foo({ a: optionsInterface, b: { c: optionsInterface } }); // okay
new Foo({ a: { b: { c: { d: { e: optionsInterface } } } } }); // okay
new Foo("whoops"); // error
new Foo({ a: optionsInterface, b: { c: "whoops" } }); // error

看起来不错。

如果要维护实际构造函数参数的类型,可以使用如下所示的泛型:

class Foo<O extends NestableOptionsInterface> {
constructor(options: O) { }
}
declare const optionsInterface: OptionsInterface;
new Foo(optionsInterface); // Foo<OptionsInterface>
new Foo({ a: optionsInterface, b: { c: optionsInterface } }); // Foo<{ a: OptionsInterface, b:{c: OptionsInterface}}>
new Foo({ a: { b: { c: { d: { e: optionsInterface } } } } }); // Foo<{ a:{b:{c:{d:{e: OptionsInterface}}}}}>

希望有帮助。 祝你好运!

相关内容

最新更新