microsoft / microsoft/TypeScript

Object spread works for unconstrained generic

Open
#38,469 2 comments 12 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.8.3

Search Terms:
generic
spread
unrestrained
unrestricted

Expected behavior:
The spread function should not compile because T is not constrained to a type that can be spread.

Actual behavior:
It compiles.

Related Issues:
https://github.com/microsoft/TypeScript/issues/30129
https://github.com/microsoft/TypeScript/pull/13288

Code

function spread<T>(t: T) {
  // This should not compile
  return { ...t };
}

// The type of `result` is `number` even though the value of `result` is `{}`
const result = spread(5);

Output
"use strict";

function spread(t) {

    // This should not compile

    return Object.assign({}, t);

}

// Result is still a number when in reality it's {}

const result = spread(5);


Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

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

Reproduce the behavior in the provided Playground link using TypeScript 3.8.3 and the listed compiler options. Read the related issue and pull request, then trace the compiler's handling of object spread for an unconstrained generic. Done means the sample is rejected as expected and the resulting type no longer incorrectly remains the argument type.

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.