arabidopsis / typescript-definitions

Apache License 2.0
69 stars 19 forks source link

Use mapped type for HashMap and BTreeMap #1

Open arilotter opened 5 years ago

arilotter commented 5 years ago

The index signature {[key: FOO]: any} is only valid for the literal types string and number (and maybe symbol). This even applies with type aliases, which are generated from newtypes in Rust - so, the following snippet won't compile.

type InstanceID = number
const instances: {[key: InstanceID]: any} = {}

error TS1336: An index signature parameter type cannot be a type alias. Consider writing '[key: number]: any' instead.

However, it appears to work correctly with mapped types - e.g, this compiles fine,

type InstanceID = number
const instances: {[K in InstanceID]: any} = {}

and it even infers correctly that typeof instances is {[key: number]: any}. This even works with the literal types like

const strings: {[K in string]: any} = {}
const numbers: {[K in number]: any} = {}