TypeScript: Why can’t I assign a valid field of an object with type { a: “a”, b: “b” }

I believe this is because objects are contravariant in their key types.

For more information see this answer.

Likewise, multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred.

const paths = ['a', 'b'] as const

type Path = typeof paths[number]

type PathMap = {
    [path in Path]: path
}

type a="a"
type b = 'b'

type c = a & b // never

{
    const BASE_PATHS = paths.reduce((map: PathMap, p: Path) => {
        let x = map[p]
        map[p] = p // same here
        return map
    }, {} as PathMap)

Intersection of a and b produces never.

If you remove as const from paths it will compile, because string & string = string

Btw, since you are using functional approach try to avoid object mutations.

Here, in my blog, you can find more information about mutations in TS

Credits to @aleksxor

Here you can find official explanation

Leave a Comment