microsoft / microsoft/TypeScript

Symbol type is incorrectly generalized when used as a property value of an object literal

Open
#36,876 6 comments 1 reaction 1 assignee View on GitHub

@rbuckton is already working on this.

Since Feb 20, 2020.

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

Description

TypeScript Version: 3.7.5

Search Terms: symbol infer type

Expected behavior:

Symbol const uniqueSymbol = Symbol() when used as property value in an object literal is inferred as unique type typeof uniqueSymbol.

Actual behavior:

Symbol const uniqueSymbol = Symbol() when used as property value in an object literal is inferred as general type symbol.

Related Issues:

Code

const uniqueSymbol = Symbol()

// Example of incorrect inference (unique symbol is generalized to type `symbol`)

const foo = {
  prop: uniqueSymbol,
}

type Foo = typeof foo  // { prop: symbol }

// Workarounds for incorrect behavior

const bar = {
  prop: uniqueSymbol as typeof uniqueSymbol,
}

type Bar = typeof bar // { prop: typeof uniqueSymbol }

const genericFactory = <T>(value: T) => ({ prop: value })

const baz = genericFactory(uniqueSymbol)

type Baz = typeof baz // { prop: typeof uniqueSymbol }

Output
"use strict";
const uniqueSymbol = Symbol();
// Example of incorrect inference (unique symbol is generalized to type `symbol`)
const foo = {
    prop: uniqueSymbol,
};
// Workarounds for incorrect behavior
const bar = {
    prop: uniqueSymbol,
};
const genericFactory = (value) => ({ prop: value });
const baz = genericFactory(uniqueSymbol);

Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "useDefineForClassFields": false,
    "alwaysStrict": true,
    "allowUnreachableCode": false,
    "allowUnusedLabels": false,
    "downlevelIteration": false,
    "noEmitHelpers": false,
    "noLib": false,
    "noStrictGenericChecks": false,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "esModuleInterop": true,
    "preserveConstEnums": false,
    "removeComments": false,
    "skipLibCheck": false,
    "checkJs": false,
    "allowJs": false,
    "declaration": true,
    "experimentalDecorators": false,
    "emitDecoratorMetadata": false,
    "target": "ES2017",
    "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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.