Skip to content

3.5.1 Regression, Generics, Indexing Constraints Not Effective #31808

Closed
@zaripych

Description

@zaripych

TypeScript Version: > 3.5.1, 3.6.0-dev.20190606

Search Terms:
Type 'string' cannot be used to index type for generic type

Code

function set_extends<
  T extends {
    [key: string]: string;
  }
>(obj: T, key: string, value: string) {
  obj[key] = value; // <-- error TS2536: Type 'string' cannot be used to index type 'T'.
}

const set_union = <T>(
  obj: T & { other: string; [key: string]: string },
  key: string,
  value: string
) => {
  obj[key] = value; // <-- error TS2536: Type 'string' cannot be used to index type 'T & { [key: string]: string; other: string; }'.
};

function set_works<T>(obj: T, key: keyof T, value: T[keyof T]) {
  obj[key] = value;
}

Expected behavior:
No compilation errors.

Actual behavior:
Compilation errors for set_extends:
Type 'string' cannot be used to index type 'T'
Compilation errors for set_union:
Type 'string' cannot be used to index type 'T & { [key: string]: string; other: string; }'

NOTE: The TypeScript version 3.4.5 gives no compilation errors

Playground Link:

NOTE: Not sure the playground is running latest TypeScript yet, so cannot be reproduced there

https://www.typescriptlang.org/play/index.html#src=function%20set_extends%3C%0D%0A%20%20T%20extends%20%7B%0D%0A%20%20%20%20%5Bkey%3A%20string%5D%3A%20string%3B%0D%0A%20%20%7D%0D%0A%3E(obj%3A%20T%2C%20key%3A%20string%2C%20value%3A%20string)%20%7B%0D%0A%20%20obj%5Bkey%5D%20%3D%20value%3B%0D%0A%7D%0D%0A%0D%0Aconst%20set_union%20%3D%20%3CT%3E(%0D%0A%20%20obj%3A%20T%20%26%20%7B%20other%3A%20string%3B%20%5Bkey%3A%20string%5D%3A%20string%20%7D%2C%0D%0A%20%20key%3A%20string%2C%0D%0A%20%20value%3A%20string%0D%0A)%20%3D%3E%20%7B%0D%0A%20%20obj%5Bkey%5D%20%3D%20value%3B%0D%0A%7D%3B%0D%0A%0D%0Afunction%20set_works%3CT%3E(obj%3A%20T%2C%20key%3A%20keyof%20T%2C%20value%3A%20T%5Bkeyof%20T%5D)%20%7B%0D%0A%20%20obj%5Bkey%5D%20%3D%20value%3B%0D%0A%7D

Related Issues:
#21760

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions