Samuel
Samuel

Reputation: 1406

creating a type for custom object in typescript

I have an object that can be

var myObj = {
  "val1": { id: 1 }
  "val2": { id: 3}
}

So, I created type as:

type MyType = { id: number }

And then created another type for myObj as:

type CustomType = {
  [key: string] : MyType
}

var myObj: CustomType = {
  "val1": { id: 1 }
  "val2": { id: 3}
}

But this does not work and gives error.

Upvotes: 1

Views: 69

Answers (2)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9893

That is because you try to use the same object myObj. You may need to define new object with different name like this:

var myObj = {
  "val1": { id: 1 },
  "val2": { id: 3}
}

type MyType = { id: number }


type CustomType = {
  [key: string] : MyType
}

var myObj1: CustomType = {
  "val1": { id: 1 },
  "val2": { id: 3}
}

PlaygroundLink

Upvotes: 2

You probably defined myObj variable twice.

Also, you forget to put a comma after { id: 1 }.

This should work


type MyType = { id: number }

type CustomType = {
  [key: string]: MyType
}

var myObj: CustomType = {
  "val1": { id: 1 },
  "val2": { id: 3 }
}

Playground

Upvotes: 1

Related Questions