Typescript-从属性名称列表创建接口



我希望能够在运行时列出接口中的所有属性,但这似乎不可能。那么,我可以创建一个包含字符串属性名称列表的接口吗?

尝试过这个,但不起作用

interface MyInterface {
prop1: string;
propsList: MyProps;
}
type MyProps = "my_prop_1" | "my_prop_2"; //these types should be string

function addProps(){
const myInterface: MyInterface = {
prop1: "hello",
propsList: {
my_prop_1: "world",
my_prop_2: "hello world"
}
}
}

尝试使用中的接口结果

类型{my_prop_1:string,my_prop_2:string}不可分配给类型"MyProps">

然后我希望以后能够使用MyProps作为字符串列表来检查另一个列表中的属性。

这可能吗?

使用属性数组,以便在运行时使用:

const myProps = ["my_prop_1", "my_prop_2"] as const;

然后你可以像这样得到你的旧类型MyProps

type MyProps = (typeof myProps)[number];

最后,对于您的界面使用映射类型:

interface MyInterface {
prop1: string;
propsList: {
[K in MyProps]: string;
};
}

最新更新