functionobjGet<T,KextendskeyofT>(o:T,k:K){returno[k];}consta=[1,"Test",{id:1,name:"test"}];constUser={id:1,name:"Test User",points:20};constid=objGet(User,"id");// numberconstpoints=objGet(User,"points");// numberconstuserName=objGet(User,"name");// string// const somethingElse = objGet(User, "nonExistent");// !Error// Argument of type '"nonExistent"' is not assignable to parameter of type '"id" | "name" | "points"'.
We can limit the possible lookup keys by using keyof T, which would prevent calling any undefined keys. This would also ensure that the correct type is written for any provided lookup key.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is a solution for the problem with
objGet
:We can limit the possible lookup keys by using
keyof T
, which would prevent calling any undefined keys. This would also ensure that the correct type is written for any provided lookup key.