typescript 使用字符串值提示接口类型?

nwo49xxi  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(184)

我正在尝试找出一种在Typescript中动态进行类型提示的方法。根据我接收到的对象,我想创建一个特定接口类型的对象(基于接收到的对象中的一些属性)。下面是一个非常基本的例子:

interface ITest {
  location: string;
  record: Record<string,unknown>[];
}

const test = {
  location: "Victoria",
  record: [
    {
      name: "matt",
      age: 29,
      is_single: false,
    }
  ]
};

if(test.location === "Victoria") {
  const interfaceName = 'ITest';

  newMessage: interfaceName = test;

}

记住这个例子,我想知道如何使用字符串值interfaceName正确地键入提示ITest
我确实知道简单地传递接口的接口名称的字符串值是不正确的,但这是想要的效果。我不是TypescriptMaven,希望能得到一些帮助!

相关问题