[英]Typescript 'tree' object definition
我不太確定要創建的對象類型的“名稱”。 我稱它為樹是因為它看起來類似於沒有關系的嵌套樹。 本質上,我想要這樣的具有嵌套定義的對象
{
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}}}}}>
希望能有所幫助。 祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.