1

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.

2 Answers 2

2

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

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

Comments

1

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

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.