1

I want to use the 'typeof' keyword on an object with mapped types to get the type of each property.

Example:

interface OnlyNumbersOrBools {
    [key: string]: number | boolean
}
const points: OnlyNumbersOrBools = {
    will: 5,
    chris: 2,
    smith: false
}

typeof points;
// it says that it is type 'OnlyNumbersOrBools'
// i want it to be an object with types: { will: number, chris: number, smith: boolean }
SimplyNo
  • 11
  • 1
  • I don't see any [mapped types](https://www.typescriptlang.org/docs/handbook/2/mapped-types.html) here. Your `OnlyNumbersOrBools` has a [string index signature](https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures). Could you [edit] your question/title? – jcalz Apr 04 '22 at 02:16
  • Once you annotate `points` as `OnlyNumbersOrBools`, you have thrown away the information you need. `typeof points` will always just be `OnlyNumbersOrBools` that way. Instead you want to check that `points` *satisfies* `OnlyNumbersOrBools` without widening. See the linked q/a for information on how to do that. One way is shown [here](https://tsplay.dev/WKqkMN). – jcalz Apr 04 '22 at 02:23

0 Answers0