[英]Typescript enforce partial interface
I have an application where I receive data in JSON format. 我有一个应用程序,可以接收JSON格式的数据。 A simplified example:
一个简化的例子:
data {
prop1: "abc",
prop2: 123,
COL_A12: "mydata",
COL_A13: "myotherdata",
}
Where I know upfront that the data will have several prop1 and prop2 property names, but COL_A12 and COL_A13 are generated, so they could've followed other naming (ie COL_A67 ). 我在哪里预先知道数据将具有多个prop1和prop2属性名称,但是会生成COL_A12和COL_A13 ,因此它们可以遵循其他命名方式(即COL_A67 )。
I enforced an interface like 我强制了一个像
interface IData {
prop1: string;
prop2: number;
}
But I cannot specify the other property's name in the interface because I don't know the exact names, although they do follow a pattern. 但是我无法在接口中指定其他属性的名称,因为我不知道确切的名称,尽管它们确实遵循模式。
Is there any way to provide a regular expression for the property name's in Typescript? 有没有办法为Typescript中的属性名称提供正则表达式?
You have no way of setting a pattern for property names. 您无法为属性名称设置模式。
What you can do is: 您可以做的是:
interface IData {
prop1: string;
prop2: number;
[name: string]: string | number;
}
So this is valid: 所以这是有效的:
let data = {
prop1: "abc",
prop2: 123,
COL_A12: "mydata",
COL_A13: "myotherdata",
} as IData;
console.log(data.prop1); // ok
console.log(data.COL_A12); // error
console.log(data["COL_A12"]); // ok
The problem is that the indexable properties are of type string | number
问题在于可索引属性的类型为
string | number
string | number
(because it can't be just string
as the object has the prop2
which is a number
), so: string | number
(因为它不能只是string
因为对象的prop2
是number
),所以:
let a = data["COL_A12"]; // typeof a is 'string | number'
let b = data["COL_A12"] as string; // typeof a is 'string'
As you receive the data, you have no way of controlling what's in it (if I understand correctly) so this interface is just to make sense of what data you get and its structure. 接收数据时,您无法控制其中的内容(如果我理解正确的话),因此此界面只是为了弄清楚您获取的数据及其结构。
If you want to then control how this data is accessed in your application then you can create a class which takes this data and exposes specific getters, for example: 如果然后要控制如何在应用程序中访问此数据,则可以创建一个类,该类接受此数据并公开特定的getter,例如:
class Data {
private raw: IData;
constructor(data: IData) {
this.raw = data;
}
public get prop1(): string {
return this.raw.prop1;
}
public get prop2(): number {
return this.raw.prop2;
}
public col(num: number): string {
return this.raw[`COL_A${ num }`] as string;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.