代码之家  ›  专栏  ›  技术社区  ›  bashleigh

类型脚本“树”对象定义

  •  0
  • bashleigh  · 技术社区  · 8 年前

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

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

    OptionsInterface {[s: string]: OptionsInterface} 有没有办法在对象的每个“级别”上使用它?

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

    但这只会有两个深度对吧?有没有一种方法可以定义我的示例对象,而不必手动添加每个深度?

    用例

    我想这样称呼我的班级

    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 期望

    1 回复  |  直到 8 年前
        1
  •  4
  •   jcalz    8 年前

    当然,你可以。

    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}}}}}>
    

    希望能有所帮助。祝你好运!

    推荐文章