将 typescript 接口转换为 json 对象

时间:2021-05-15 19:43:03

标签: typescript

有没有可能将 typescript 接口转换为 json 对象的方法?

我有一个函数,我想接收一个代表接口的参数。

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

我想像这样使用这个函数:

interface InterfaceX {
  a: string;
  b: boolean
}

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

有没有办法让我得到这个 const x?

1 个答案:

答案 0 :(得分:0)

不,接口在运行时不存在,所以这是不可能

相关问题