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



我正试图找出一种在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

我知道简单地传递接口的接口名称的字符串值是不正确的,但这是想要的效果。我不是Typescript方面的专家,希望能得到一些帮助!

type ITest = {
location: 'Victoria';
record: Record<string, SomeType>[];
} | {
location: 'Georgia';
record: Record<string, OtherType>[];
}
if (test.location === "Victoria") {
// `test.record` is of type `Record<string, SomeType>[]` in this block
} else {
/ `test.record` is of type `Record<string, OtherType>[]` in this block
}

最新更新