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

从Typescript接口用空键值初始化对象

  •  0
  • JulienRioux  · 技术社区  · 6 年前

    interface 将存储初始空值的:

    // Interface I'm looking to mock
    interface IMyInterface {
      name: string;
      posts: string[];
    }
    

    从这个接口,我需要根据接口键和类型用初始值初始化一个对象,比如:

    const initObjFromInterface = (interface: any) => {
      // do something
      return initObject;
    }
    
    const initializedObj = initObjFromInterface(IMyInterface);
    

    注意,我不知道作为参数传递的接口的键 initObjFromInterface 功能!

    initobjfrom接口

    console.log(initializedObj);
    
    /* should output:
    {
      name: "",  // empty string
      posts: []  // empty array
    }
    */
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   Józef Podlecki    6 年前

    你不能像评论中说的那样做。

    const emptyObject: IMyInterface = {
      name: '',
      posts: []
    }
    

    并将一些唯一值传递给函数,以便它可以确定要获取接口的哪个空对象。

    const initObjFromInterface = <T>(interfaceName: string) => {
      if(interfaceName === "IMyInterface") {
        return emptyObject as any as T;
      }
    
      return {} as T;
    }
    

    我相信上面的代码可以设计得更好(也许是类型保护和类型推断)