1

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

J2ghz
  • 632
  • 1
  • 7
  • 20

1 Answers1

1

This looks like it works:

function f2<T extends Record<any, any>>(item: T, key: StringOnlyKeys<T>): string {
    return item[key];
}

I'm not 100% sure why, but my guess is that TypeScript won't implicitly restrict generic type parameters. So, if you use an unrestricted <T>, that could be a number (for instance), and rather than saying "ah, well that means this function can't possibly be called with a number", instead the compiler says "I have no idea what StringOnlyKeys<number> means, so anything involving it must be any".

General Grievance
  • 4,555
  • 31
  • 31
  • 45
user31601
  • 2,482
  • 1
  • 12
  • 22