Reputation: 32758
I have data that looks like this:
var abc = [{ "id": 1, "name": "x" }, { "id": 2, "name": "x" }]
Can someone tell me how I can declare a datatype for this in Typescript ? Can I go so far as to declare that the objects contain and "id" and "name" field?
Upvotes: 1
Views: 187
Reputation: 123851
We can use interface defined explicitly or we can just use inline type definition
// inline type
var abc: {id:number;name:string}[] =
[{ "id": 1, "name": "x" }, { "id": 2, "name": "x" }]
// wrong
// var abc: {id:number;name:string}[] = [{ x : 1}]
// explicit interface
interface IData{
id:number;
name:string;
}
var def: IData[] =
[{ "id": 1, "name": "x" }, { "id": 2, "name": "x" }]
// wrong
// var def: IData[] = [{x : 1 }]
check both here
Upvotes: 2