1

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?

1
  • You can just declare an interface for things that have an int id and a name string. One of the things TypeScript got right is that it has structural typing. What have you tried so far and where are you stuck? Commented Jul 27, 2014 at 14:52

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.