Unknown-ish types
I am building a simple drag and drop library, nothing fancy - I've got to a point where the first prototype works, my issue now is that I have a Vue composable (all you need to know if you're not familiar is that it's basically like a hook, a function that takes some parameters), the user using the library would send up an array of
lists
that will have drag and drop capabilities.
Now, the list will just be an Array
of Arrays of objects
but I don't know what's going to be inside of those objects, all I know is they will definitely need to have an id
, how do I go about assigning types to the singular object
?17 Replies
what I would like to say is -
const list = Array<MyType>
but my type is kind of unknown, I don't really know what people are going to have in their lists, is it generics I need to look at? Cause any
is not really acceptable, don't want people sending up something that's not an object without at least an id
yes generics is pretty much what you are looking for maybe share some code for more context
I have a function like:
export function useDragDrop(items: Array<object>) { // do stuff }
what I need to define is that object type, but I think type object is probably good enough as I was reading here: https://stackoverflow.com/questions/18961203/any-vs-object
I can then check if at least id
is present in every item of the list at runtime
then whatever else people pass in that object I don't really carejust
T will then be a union of the types of the objects inside your array
but i think you should only allow users to pass objects with an id in the first place
i mean that's the whole point of ts in the first place
catching bugs on runtime is the js mindset
Yeah fair point - I’ll do some more reading about generics
Thanks!
no problem
In the end I solved by doing something like this:
There was a gotcha with Vue's reactivity that needed sorting out but it now seems to be behaving as expected
is items a 2 dimensional array?
yeah
it'd basically be a collection of lists - I guess actually I need to take into account that someone might want to pass only one list
good point
you can also write T[][] which I find prettier
haha
ahh! yeah, it's also less confusing, thanks 🙂
np
another opinionated thing would be to use type instead of interface but you do you
what's the reasoning behind it?
I've always used them interchangeably, like, if I used interface somewhere else I'll use interface again kinda thing
great short video:
https://www.youtube.com/watch?v=zM9UPcIyyhQ
Matt Pocock
YouTube
TypeScript: Should you use Types or Interfaces?
Become a TypeScript Wizard with Matt's upcoming TypeScript Course:
https://www.totaltypescript.com/
Follow Matt on Twitter
https://twitter.com/mattpocockuk
ah I think I've seen his previous video hahah
thanks by the way, very helpful!
you're welcome
just pushed a first prototype here if you're interested: https://github.com/alextana/dragdrop-lib / demo: https://dragdrop-lib.vercel.app