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

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.