#How to require a value to at least partially match a type?

12 messages · Page 1 of 1 (latest)

jade summit
#

I think this is possible but I'm having a brain fart.

type HasHeight = { height: number }

function doThing = (creature: ??) {
  // I don't care what gets passed in, so long as it's shape at least partially `HasHeight`,
  // e.g. it has a `height` property that is a number.
}
mossy pivot
#

@jade summit

type HasHeight = { height: number }

function doThing = (creature: HasHeight) {}
jade summit
#

the issue with that is, it override sthe type if that function calls a callback or something and passes it back

mossy pivot
#

Oh, if doThing returns the creature at the end?

#

Yeah, in that case you'd want it generic:

function doThing = <T extends HasHeight>(creature: T) {
   // do stuff
   return creature;
}
jade summit
#

o duh, i was close to that but over complicating it

#

ok the way i hav eit seems to work

#

basically

type HasHeight = { height: number }

function doThing = <T>(creature: T & Required<HasHeight>) {}
#

altho idk if the Required is really necessary

#

i guess so tho in case the type being passed in has height as optional

mossy pivot
#

Yeah, Required doesn't do anything. That utility removes optional types from the passed type.

#

I think the extends version is a bit nicer as it'll keep the types (and potential error messages) simpler.