【问题标题】:Initialize an object with empty key values from a Typescript interface从 Typescript 接口使用空键值初始化对象
【发布时间】:2020-09-04 16:03:04
【问题描述】:

我希望从 typescript 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 函数的接口的键!

initObjFromInterface函数的返回值应该是:

console.log(initializedObj);

/* should output:
{
  name: "",  // empty string
  posts: []  // empty array
}
*/

【问题讨论】:

  • 这能回答你的问题吗? Typescript interface default values
  • 谢谢@ritaj,但这不是回答问题。我需要在不知道接口将通过空值传递什么的情况下初始化对象,在示例中为空字符串和空数组。
  • 不要认为你可以将接口作为参数传递给函数,因为接口只是一种类型,不能用作值
  • 你是对的@Yousaf,可能需要创建一个对象或使用代理来这样做,但现在不知道如何解决这个问题!

标签: javascript typescript types interface mocking


【解决方案1】:

您不能像 cmets 中所述那样做。

您必须将空对象的实例存储在某处。

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

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

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

  return {} as T;
}

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

【讨论】:

  • 谢谢,但这不适用于我的情况。我需要从一个接口开始并从那里创建对象。我很确定它可以以某种方式完成,所以我会继续努力,我会在有人找到之前写下答案!
  • 让我知道,因为我也想知道如何将打字稿类型具体化到 javascript 中!
猜你喜欢
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 2013-06-27
  • 2013-09-02
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
相关资源
最近更新 更多