You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functioncacheItem<Textendsany,Kextends{[KinkeyofT]: T[K]extendsstring ? K : never}[keyofT]>(item: T,key: K){constvalue: string=item[key];// is typed as stringvalue.replace;}
{K: string} is not saying what you intend to say, since K is just a literal key there (e.g., foo.K = "oops"). Instead, you can use a mapped type such as {[P in K]: string} or the equivalentRecord<K, string>. (Eventually you may be able to use K directly as an index signature as in {[k: K]: string} but that is not currently supported.)
functioncacheItem<Kextendsstring>(item: Record<K,string>,key: K){constval=item[key];// should be typed as string (is)}constmyItem={id: "string",count: 1234}cacheItem(myItem,"id")// workscacheItem(myItem,"count");// Error
Search Terms
enforce key type of generic type
Suggestion
I would like to specify that a property, defined as a function argument, of a generic type is of a specific type
Use Cases
I want to pass an item and a key to a function and specify that the type of the property specified by the key is a certain type
Examples
Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: