Functions type for key of objects with specific key

Hey, are there any typescript wizards here that could help? I've been trying for a while already but don't really get there. I would like to type a function that takes in two arguments: an arbitrary object as the first argument and for the second argument a key of that object but only allow keys with e.g. a number as an associated value. What's the best way to do this? This is what I have so far. I only want to allow valueKeys which have a type number as a value. Thanks!
const BarChart = <
T extends { date: Date },
K1 extends keyof T,
>({
data,
valueKey,
}: {
data: T[]
valueKey: K1
}) => {...}
const BarChart = <
T extends { date: Date },
K1 extends keyof T,
>({
data,
valueKey,
}: {
data: T[]
valueKey: K1
}) => {...}
9 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
kliyer
kliyer2y ago
Thanks, that's exactly what I needed!
☘
2y ago
is that normal in your line of work
kliyer
kliyer2y ago
Haha I just love my typesafety. I'm just trying to get better at typescript which is why I'm trying these challenges. This was actually for my own product
☘
2y ago
okay adding these types of types (pun) adds maintenance burdens when the args change
kliyer
kliyer2y ago
Can you give an example where that would be a problem?
☘
2y ago
if the function needs different types of inputs thus changing the typing that's what I meant
kliyer
kliyer2y ago
Would it be better to use an accessor function then? Basically I wanna be able to pass a list of objects as a dateset and specify a property of every object to be used for the y value in the chart. That y value has to be of type number
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server