Repository navigation
Required<T> optional properties type validation will not work #29991
Description
Activity
jack-williams commented
on Feb 20, 2019 CollaboratorMore actionsThis looks to be related to variance markers used for generic mapped types---a very similar problem to #29698. When relating
aandb, I believe it is just relating the type arguments in a covariant way, which holds for assigning{ a?: 1; x: 1 }to and from{ b?: 1; x: 1 }. The variance markers do not reflect how the keys of the type arguments are used.You can see behaviour by replacing
Requiredwith a structurally equivalent, but different alias. Variance markers are not used in this instance, and type checking falls back to structural checking. The error correctly gets flagged in this case.type Required2<T> = { [P in keyof T]-?: T[P]; }; const a: Required<{ a?: 1; x: 1 }> = { a: 1, x: 1 }; const b: Required2<{ b?: 1; x: 1 }> = { b: 1, x: 1 }; export let A = a; export let B = b; A = b; // Error! B = a; // Error!
I've been wrong on this before though. You'll most likely need Anders Hejlsberg (@ahejlsberg) or Wesley Wigham (@weswigham) to give a definitive answer.
Thanks for looking into this Jack Williams (@jack-williams).
It was a difficult problem to understand for me.
I was saved because it provided information.Once it is written as follows, it will be as intended, so it seems to be temporarily resolved.
type Required2<T> = Required<{ [P in keyof T]-?: T[P]; }>; const a: Required2<{ a?: 1; x: 1 }> = { a: 1, x: 1 }; const b: Required2<{ b?: 1; x: 1 }> = { b: 1, x: 1 }; export let A = a; export let B = b; A = b; // Property 'a' is missing in type 'Required<{ b: 1; x: 1; }>' but required in type 'Required<{ a: 1; x: 1; }>'. B = a; // Property 'b' is missing in type 'Required<{ a: 1; x: 1; }>' but required in type 'Required<{ b: 1; x: 1; }>'. a.b; // Property 'b' does not exist on type 'Required<{ a?: 1; x: 1; }>'. b.a; // Property 'a' does not exist on type 'Required<{ b?: 1; x: 1; }>'.
This is fixed in
master.jack-williams commented
on Mar 6, 2019 CollaboratorMore actionsWesley Wigham (@weswigham) I can't seem to reproduce: 5bd73f5. It should error on the first two assignments, right?
(P.S. excuse my spelling)
Your baselines are right - getting an error on those two accesses is intended, since the
Requiredtype is meant to strip them out, and the assignments should all be allowed, since they both evaluate to{x: number}.jack-williams commented
on Mar 6, 2019 CollaboratorMore actionsIs
Requirednot meant to remove?modifiers, rather than strip out optional properties?Ah, derp, you're right - I was confusing it with a
RequiredKeysfunction I'd been looking at.hmmm yeah, those assignments shouldn't work. Hmm.- locked as resolved and limited conversation to collaborators
on Oct 21, 2025
TypeScript Version: 3.2.0-rc <= 3.4.0-dev.20190220
Search Terms: Required
Code
Expected behavior:
When it is "3.1.6" it will be like that.
Actual behavior:
No Error
Playground Link:
link
Related Issues: