镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Intersection breaks generic key field inference #26409

Closed

Description

TypeScript Version: 3.1.0-dev.20180810

Code

const f = <T extends { [K0 in K]: string; } & { cool: string; }, K extends keyof T>(t: T, k: K) =>
{
  const s: string = t[k];
};

Expected behavior: Successful compilation

Actual behavior: I get the following error:

error TS2322: Type 'T[K]' is not assignable to type 'string'.

     const s: string = t[k];
           ~

Playground Link: Link

Additional Notes: This compiles successfully (link):

const f = <T extends { [K0 in K]: string; } & { cool: string; }, K extends keyof T>(t: T, k: K) =>
{
  const s: string = t['cool'];
};

as does this (link):

const f = <T extends { [K0 in K]: string; }, K extends keyof T>(t: T, k: K) =>
{
  const s: string = t[k];
};

Activity

  1. added
    BugA bug in TypeScript
    and removed
    Needs InvestigationThis issue needs a team member to investigate its status.
    on Aug 27, 2018
  2. ahejlsberg commented on Aug 27, 2018

    @ahejlsberg
    Member

    The issue here is that we're not examining all constraints of indexed access types in type relations, rather we jump straight to base constraints.

    In exploring the issue I also discovered that this errors where it shouldn't:

    const f = <T extends { [P in K | "cool"]: string; }, K extends keyof T>(t: T, k: K) =>
    {
        const s: string = t[k];
        t.cool;  // Error, but shouldn't be
    };

    I'll put up a PR with a fix shortly.

  3. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions