I have looked at similar questions, but they stop one step short of what I need. For example solution from this question doesn't work when I try to use it in a function: Playground
What I need is a function, which takes item T, and a key of T such that the compiler knows the key always refers to a string field, and so the return type of item[key] is string:
function f2<T> (item: T, key: StringOnlyKeys<T>): string {
return item[key] as string;
}
This doesn't compile in the generic case, see playground link