简体   繁体   English

将typescript接口转换成json object

[英]Convert typescript interface into json object

Is there a possible way to convert a typescript interface into a json object?有没有办法将 typescript 接口转换为 json object?

I have a function that I would like to receive a param that represents an interface.我有一个 function 我想接收一个代表接口的参数。

function parseIntoResponse(input: any): MyNewInterface {
  const response = {
    description: 'lorem ipsum',
    schema: [],
  };

  const keys = Object.keys(input);
    
  keys.forEach(key => {
    const schema = {
      name: key,
      type: JSON.stringify(input[key]),
    };
    
    response.schema.push();
  });

  return response;
}

And I would like to use this function like this:我想像这样使用这个 function :

interface InterfaceX {
  a: string;
  b: boolean
}

const x = InterfaceX parsed as an object;
const y = parseIntoResponse(x);

Is there a way for me to get this const x?有没有办法让我得到这个 const x?

No, interfaces don't exist at runtime, so this is not possible .不,接口在运行时不存在,所以这是不可能的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM