Typescript: the rules of assertion to partial type

Viewed 173
type Rec = Record<'a', number>

const a: Rec = { b: 1 } 
// Error: Object literal may only specify known properties, and 'b' does not exist in type 'Rec'

const b = { b: 1 } as Rec
// Error: Conversion of type '{ b: number; }' to type 'Rec' may be a mistake [...]

type PRec = Partial<Rec>

const pa: PRec = { b: 1 }
// Error: Object literal may only specify known properties, and 'b' does not exist in type 'Partial<Rec>'

const pb = { b: 1 } as PRec
// ALL OK. o_O

playground

Interfaces behave just the same – so I assume it's not because of index signature. It's somehow because of Partial.

Docs says, that

Basically, the assertion from type S to T succeeds if either S is a subtype of T or T is a subtype of S

So, the logic should be: { b: 1 } is a subtype of { a?: number }

But this means, that here { a?: number } is not considered as 'an object with a: number prop, or an empty object' – instead, it's 'ANY object, which occasionally may have a: number prop'.

Does this mean that optional keys do not restrict the shape of object? Can I find this in docs, and is it another known issue / technical limitation / assumed compromise / works-as-intended / etc of TS?

0 Answers
Related