Skip to content

Partial mapped types on constrained generics should allow object literals to specify only known keys #23015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
dhruvrajvanshi opened this issue Mar 30, 2018 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@dhruvrajvanshi
Copy link
Contributor

There's some odd behaviour with mapped types on generic types with extends constraints.

TypeScript Version: 2.9.0-dev.20180330

Search Terms:
generic constraint

Code

type Entity = {
  id: string;
};

function f<T extends Entity>() {
  const where: { [K in keyof T]?: T[K] } = {
    id: "asdf"
  }; // this throws type error
  where.id = "asdf"; // this is valid
}

Expected behavior:
No type error

Actual behavior:
Getting type error on first assignment: Type '{ id: "asdf"; }' is not assignable to type '{ [K in keyof T]?: T[K]; }'.

Playground Link:

Related Issues:
None that I know of

The above code snippet throws a type error even though it is safe. Presumably, because only a subset of keys of T are known at this point, the compiler can't check if the given object literal contains all keys of T. However, the type is partial and skipping the unknown keys is perfectly safe. It would be nice if this could be detected and allowed or at least a better error be produced. I spent way too much time trying to figure out why this didn't work.

@dhruvrajvanshi dhruvrajvanshi changed the title Partial mapped types on constrained generics should allow object literals to specify known keys Partial mapped types on constrained generics should allow object literals to specify only known keys Mar 30, 2018
@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 30, 2018
@RyanCavanaugh
Copy link
Member

Duplicate #13442 and others

@microsoft microsoft locked and limited conversation to collaborators Jul 25, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants