DEV Community

Discussion on: Writing a type-safe prop function in Typescript

Collapse
 
cdimitroulas profile image
Christos Dimitroulas • Edited

Thanks for the suggestion!

That would certainly work and has the benefit of autocompletion for the key but it unfortunately requires you to pass the generic types to specify what T and K should be (e.g. prop<User, "email">("email")). Without that, the code doesn't compile at all:

const prop = <T, K extends keyof T>(k: K) => (t: T): T[K] => t[k]

// Argument of type 'string' is not assignable to 
// parameter of type 'never'.
prop("email") 
Enter fullscreen mode Exit fullscreen mode

It's actually a strangely difficult function to implement in Typescript without any tradeoffs. I have a PR open for the fp-ts library to add a prop function and we iterated over several implementations - you can see the discussion here if you're interested :)

Collapse
 
waynevanson profile image
Wayne Van Son

I don't really use it unless it's inline like a function, so it satisfies my needs. PR looks good, nice type Def. Having a standalone prop function to apply later looks good!