microsoft / microsoft/TypeScript

Generic type not assignable if extends type with optional field and passed object does not include the optional field

Open
#38,635 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.9.2

Search Terms:
optional generic "not assignable"

Code

const foo = <V extends { s?: string }>(v: V) => {};

// This works:
foo({ s: "1", v: 2 });

// This doesn't work:
foo({ v: 2 }); // Argument of type '{ v: number; }' is not assignable to parameter of type '{ s?: string | undefined; }'. Object literal may only specify known properties, and 'v' does not exist in type '{ s?: string | undefined; }'.

Compare with

const bar = <V extends { }>(v: V) => {};

// Both work:
bar({ s: "1", v: 2 });
bar({ v: 2 });

Expected behavior:
Both statements in the first snippet should compile.

Actual behavior:
foo({ v: 2 }); doesn't compile for const foo = <V extends { s?: string }>(v: V) => {};

Playground Link:
https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZiEMC8MA8A1GBTAHlbMAEwhgG8YIB+ALkqgCcBLMAcxgF8A+ACgDc6GAJQou5ALAAoKRwDcUhCB4UIdAEQBGNQBoYAmACZOQ+ZMXK9dIxxNSpoSLABGAQwYp0WPAWKkK3fkERZDEyOTtJAHpImAAhECgACxgAdxAGAGsaKVcGC1UYTR1LQ2NTXIt9axMgA

Related Issues:

Possible remotely related... https://github.com/microsoft/TypeScript/issues/13747

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the TypeScript 3.9.2 reproduction in the provided Playground link and compare the two generic calls. Trace the type-checking behavior for excess properties on a generic constraint with an optional field. Done means both calls in the first snippet compile without changing the behavior shown for the second snippet.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.