将 TypeScript 接口转换为 JSON 对象

3

有可能将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);

有没有办法让我获得这个常量x?
1个回答

0
不,接口在运行时不存在,因此这是不可能的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接