Skip to content

It's not possible to assign to string to T[keyof T] where T extends { [key: string]: string } #34591

Closed
@blixt

Description

@blixt

TypeScript Version: 3.7.0-dev.20191018

Search Terms: keyof string index record not assignable

Code

function test<T extends { [key: string]: string }>(map: T) {
    const key: keyof T = "hello"
    map[key] = "hi there"
}

(see playground for a more real example)

Expected behavior: Infer that the types accepted by the function will allow string key assignment (to string value). Since an interface with members incompatible with the string->string signature is invalid, anything that extends Record<string, string> should also have string keys with string values.

Actual behavior: An error such as:

  • Type 'string' is not assignable to type 'T[keyof T]'.
  • Type 'string' cannot be used to index type 'T'.
  • Type 'string' is not assignable to type 'T[Extract<keyof T, string>]'.

The last one is if you attempt to do the assignment inside of a for (const key in map) loop. In this case especially, you'd think that even if there were somehow other properties with other types on the object (eg symbol or number indices), that it's narrowed down to just strings.

Playground Link: http://www.typescriptlang.org/play/?ts=3.7-Beta#code/GYVwdgxgLglg9mABFApgZygHgCqJQD1TABM1EBvRAbQGsUBPALkQwCcYwBzAXWbY86IAvgD4AFAFsAhgAdm2AJQUAUIjWIICDIjr1EAXkQAiABYoANubhHV6gPR2NWqDobNdcYIlyHTFqzbqiA5OYNq6fFDsXAbGZpbWtmrSMrQM3LGmMMhmrCg2QsrKIQCCiBJweaEQeah4+FISMuYojEWgkLAI5VJ0AGpS5iDoAKoyMiisOPVEpIgASiiarMSY-FwANCxRAiLiAG6Dw2jyCvIqQZphLnloIOZQzAAKUqywgzgiseSFQcCViDEV3CDEQHEQhyG6CU5CSQUQt3uUDS9AyhkhxxR3AAdFA4GMJqwAMJSNAoMQKOG-eyOADKMGIKDAcFQzAAkogAO4wNAmMEuTmkxAyOBoNAwABGLWQcEQnBArykYFQKAR6CRYLImiaLTquFyKGxRrhtRArCQiIeiCF2GUhWUwJcIHGk1i0n6R1GLtYYkoYEarWMACE4BKjFsZKxPOhxQhmEYg6S6FAJYNzIgnuYpPRJkZhJSgA

Related Issues: #29295 was similar but possible to work around.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions