microsoft / microsoft/TypeScript

Suggestion: perform excess property checks when spreading an inline object literal

Open
#39,998 20 comments 122 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback 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:

Code

declare const someCondition: boolean;

type MyObject = { foo: number; bar?: number };

const a: MyObject = {
  foo: 1,
  bar: 2,
  // ✅ Error because `invalid` is an excess property
  invalid: 3,
};

const b: MyObject = {
  foo: 1,
  ...(someCondition
    ? {
        bar: 2,
        // ❌ `invalid` is an excess property, but we don't get an error here
        invalid: 3,
      }
    : {}),
};

In the example above, I only want to include specific properties when a condition is met. That's the only reason I'm using spread here.

I understand that TypeScript only performs excess property checks inside of object literals. Currently this does not include inline object literals which are being spread inside of another object literal.

In my experience this is a very common code pattern so it would be great if TypeScript handled this.

Expected behavior:

An error

Actual behavior:

No error

Playground Link:

Related Issues:

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 reproducing the supplied TypeScript 3.9.2 example and compare the direct object-literal assignment with the conditional spread case. Investigate the compiler's excess-property checking for inline object literals used in spreads. Done means the shown invalid property produces an error in the spread case without breaking valid conditional spreads.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.