简体   繁体   English

如何在typescript界面添加变量作为键名?

[英]How to add variable as key name in typescript interface?

This is how my object would look like.这就是我的 object 的样子。 This is very small version of object and I have to deal with large object.这是 object 的非常小的版本,我必须处理大的 object。

const obj = {
    name: 'name_key',
    details: 'details_key',
    profile: 'profile_key',
}

So, if we want to use value of this object in another object then we can use it like:所以,如果我们想在另一个 object 中使用这个 object 的值,那么我们可以像这样使用它:

const newObj = {
    [obj.name]: 'some_value',
    [obj.details]: 'some_value',
    [obj.profile]: 'some_value',
}

So, here newObj would become like:所以,这里的 newObj 会变成这样:

newObj = {
    'name_key': 'some_value',
    'details_key': 'some_value',
    'profile_key': 'some_value',
}

The same way I want to use it with interface but I'm unable to do so.就像我想将它与界面一起使用一样,但我无法这样做。

interface User {
    [obj.name]: string;
    [obj.details]: DetailsInterface;
    [obj.profile]: ProfileInterface;
}

I have tried this approach but it throws error like "A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type."我已经尝试过这种方法,但它会抛出错误,例如“接口中的计算属性名称必须引用类型为文字类型或‘唯一符号’类型的表达式。” Here DetailsInterface and ProfileInterface are also interface.这里的 DetailsInterface 和 ProfileInterface 也是接口。

I have tried union approach but it doesn't work as all the keys have different types of interface or data type.我尝试过联合方法,但它不起作用,因为所有键都具有不同类型的接口或数据类型。

you can't create a strong-typed interface for something that is defined at runtime, that's not how TypeScript works.您不能为运行时定义的内容创建强类型接口,这不是 TypeScript 的工作方式。

What you could do instead is having a broader interface/type definition that will match with that obj , like this:你可以做的是拥有一个更广泛的接口/类型定义来匹配那个obj ,就像这样:

type User = Record<string, any>

But if obj is statically defined, you can generate a interface from it, like so:但是如果obj是静态定义的,你可以从它生成一个接口,像这样:

代码

I'm unsure if this was what you were looking for tho.我不确定这是否是您要找的东西。

I found solution.我找到了解决方案。 The object that we have defined is mutable.我们定义的 object 是可变的。 So if we use like所以如果我们使用像

const obj = {
    name: 'name_key',
    details: 'details_key',
    profile: 'profile_key',
} as const;

it becomes unmutable and all the fileds have string value.它变得不可变,所有的字段都有字符串值。 Now we can use this object fiels as computing keys name in interface as shown below现在我们可以使用这个 object 字段作为界面中的计算键名称,如下所示

interface User {
    [obj.name]: string;
    [obj.details]: DetailsInterface;
    [obj.profile]: ProfileInterface;
}

So finally interface User becomes like所以最后界面用户变得像

interface User {
    name_key: string;
    details_key: DetailsInterface;
    profile_key: ProfileInterface;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM