After researching similar questions, I have found that none of them provide the exact solution I am looking for. For instance, the solution from this question falls short when used within a function: Playground
What I require is a function that takes an item T and a key of T such that the compiler can be confident the key always points to a string field, and therefore the return type of item[key] will be a string:
function f2<T> (item: T, key: StringOnlyKeys<T>): string {
return item[key] as string;
}
This does not compile in the generic case, as shown in this playground link