I created the following types from a constant array <const>['a', 'b]
:
const paths = <const>['a', 'b']
type Path = typeof paths[number]
type PathMap = {
[path in Path]: path
}
Path
equals to "a" | "b"
PathMap
equals to {a: "a", b: "b"}
Then the following code compiles fine:
const BASE_PATHS = paths.reduce((map: PathMap, p: Path) => {
map['a'] = 'a'
return map
}, <PathMap>{})
This also works:
const BASE_PATHS = paths.reduce((map: PathMap, p: Path) => {
return { ...map, [p]: p }
}, <PathMap>{})
But the following code does not compile:
const BASE_PATHS = paths.reduce((map: PathMap, p: Path) => {
map[p] = p
return map
}, <PathMap>{})
Which gave me this error at map[p] = p
:
TS2322: Type 'string' is not assignable to type 'never'. Type 'string' is not assignable to type 'never'.
Why is this the case?
Thanks for helping!