[英]Dynamic TypeScript key name
I am using TypeScript and i am wondering how can i "type" the following object.我正在使用 TypeScript,我想知道如何“键入”以下 object。
{
"code": 52,
"somerandomstring123":"Some Data"
}
The thing is, that the KEY NAME somerandomstring123
is dynamically generated string and is not constant.问题是,KEY NAME somerandomstring123
是动态生成的字符串,不是恒定的。 So for example, the JSON could've been like this:例如,JSON 可能是这样的:
{
"code": 52,
"someOTHERstring456":"Some Data"
}
I tried using [key:string]: string
like this:我尝试使用[key:string]: string
,如下所示:
interface SomeObjectData {
code: number;
[target: string]: string;
}
but it returns an error of: Property 'code' of type 'number' is not assignable to 'string' index type 'string'.
但它返回错误: Property 'code' of type 'number' is not assignable to 'string' index type 'string'.
you can use the union type for the target.您可以使用联合类型作为目标。
interface SomeObjectData {
[target: string]: string | number;
code: number;
}
const data:SomeObjectData = { code: 12}
Try this:尝试这个:
type SomeObjectData = {
[key: string]: string; // dynamic properties
} & {
code: number; // static properties
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.