Objects of objects of a certain type
I am trying to create an object whose keys can be anything, but values are of a certain type.
Each object is essentially a link, that has a certain shape. Then I put them in a wrapper object like this, however each object within is typed indivdually instead of the overall object. The problem is when I try and loop over the wrapper object LINKS, it is not giving me typesaftey. How do i fix this?
17 Replies
like this?
thankyou, but when i tried this, there is no autocomplete when you do LINKS.
oh then you might just want to use what you already had and add as const to the LINKS object
i agree, but the wrapper object still isnt typed as containing only LinkProperties
or maybe ts doesnt allow doing that in general, im not sure, im very new to ts
yeah i understand not sure how to solve it tho
all good, thanks for you help anyway
maybe satisfies: but its more like what you had here.
https://tsplay.dev/wOLy7N
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
i agree, thanks for the help
just wanted to add that the
Record
type does the same thing as this but tiny bit shorter
doesnt change all that much but cool to knowyeah right thank you
but consting an object with dynamic keys is not a thing?
hovering
LinksType
in this case LinksTypes possible keys are defined by the keys of some object
you have to define the type somewhere
either it can be super generic (
Record<string, LinkProperties>
)
or super specific (as const
)
but the whole point of a type is to know what your getting in advance
so if the type is super dynamic then you might have some challenges getting the level of autocomplete you are hoping forA type cant refer to itself
So somewhere you have to tell typescript every possible value for a key in your object
If you cant describe that as a list of specific things (either by actually writing it out, or by referencing another type) the best you can do is just
string
(or whatever type your using to index)that makes sense
the type would have to change as you only want to type the values first and later infer the keys
which is not a thing in ts