1

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 
1
  • 1
    Your question doesn't seem right, your type signature is not declared properly and would actually give you An index signature parameter type must be either 'string' or 'number' error even if it was declared properly. Commented Nov 30, 2020 at 19:12

2 Answers 2

3

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 }
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

You could add some more info explaining why a record should be used instead of a type.

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.