【发布时间】: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