Reputation: 3389
How can I represent the data model in typescript for the below structure? The key-values after id
(like a1
,a2
) are dynamic, which means there can be different key-value there.
{
name: 'SampleName',
description: 'Sample description',
id: '_3434',
a1:'abc',
a2:'xyz'
}
Trying something like below doesn't make sense, since we don't have others
in the data.
interface TestData{
name:string;
description:string;
id:string;
others:any;
}
Upvotes: 1
Views: 27
Reputation: 250036
You can define a type that has some known properties and a index signature for dynamic data. The index signature needs to be compatible with all properties, but in this case you only have strings so it isn't a problem:
interface TestData {
name: string;
description: string;
id: string;
[name: string]: string
}
You should be careful with such types, they will allow indexing by anything so this will not throw any compiler error:
declare let a: TestData;
a.notHere // ts is ok with this since the index signature is there
Upvotes: 2