#Why new Map causes no type inference

8 messages · Page 1 of 1 (latest)

pallid rover
#

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAglC8UDeAoK6oEMBcBnYATgJYB2A5gNwoC+KKokUAwgrANoC6VKAxgPYl8WHC0QwCBTCAB0AMwJ8AtgAo0GEhADuUALKYwqjEahskOKAHJMFgDRQAJtigBGah2mL9yosAiL4AHwmPn7SmHYhihwAlGro0dIAbpgANgCuELjKsdFAA

type A = {
    a:string;
}

type C = A[];

const aa:C = Array.from( // Why I don't see any error as `d` shouldn't be accepted?
    new Map(
        [{a: 'a', d: 1}].map(item=> [item.a, item])
    ).values()
)


fleet cloakBOT
#

@pallid rover Here's a shortened URL of your playground link! You can remove the full link from your message.

piotr8587#0

Preview:```ts
type A = {
a: string
}

type C = A[]

const aa: C = Array.from(
new Map(
[{a: "a", d: 1}].map(item => [item.a, item])
).values()
)```

inland fox
#

typescript allows excess properties

pallid rover
#

Is there a solution to check excess properties and have an error?

inland fox
summer estuary
#

import { Exact } from 'exact-object'

type A = Exact<{ a: string }, ['a']>

type AArr = A[];

// OK
const aArr: AArr = Array.from(
    new Map(
        [new Exact({ a: 'a' }, ['a'])].map(item=> [item.a, item])
    ).values()
)

// Err
const aArr2: AArr = Array.from(
    new Map(
        [new Exact({ a: 'a', d: 'd' }, ['a', 'd'])].map(item=> [item.a, item])
    ).values()
)
summer estuary
#

exact objects have to be created like new Exact({ a: 'a' }, ['a']) because we don't know whether the object passed to it has extra properties not known in the type. So the array of keys after acts as a control to prevent extra keys.