Alex
Alex

Reputation: 1420

TypeScript type for object of objects?

What would be the correct typescript type of something like

const test: MyType = {
  foo: { value: 1 },
  bar: { value: 2 }
}

something like

type MyType {
  [key: any]: {
    value:number
  }
}

results in

Object literal may only specify known properties, and 'foo' does not exist in type 

Upvotes: 1

Views: 1831

Answers (2)

abhishek khandait
abhishek khandait

Reputation: 2157

const test: Record<string, {value: number}> = {
    foo: { value: 1 },
    bar: { value: 2 }
};

Upvotes: 1

pzaenger
pzaenger

Reputation: 11973

An index signature parameter type must be either string or number:

type MyType = {
    [key: string]: { value: number; };
};

const test: MyType = {
    foo: { value: 1 },
    bar: { value: 2 }
};

Or, using Record:

const test: Record<string, { value: number }> = {
    foo: { value: 1 },
    bar: { value: 2 }
}

const test: Record<'foo' | 'bar', { value: number }> = {
    foo: { value: 1 },
    bar: { value: 2 }
}

Upvotes: 3

Related Questions