By Matthew Garcia
There are cases in Flow where you’ll want to create a generic function or class, but want to limit what can be passed as a type argument.
Let’s say you have a class that wraps a Map, but makes a shallow copy before inserting:
Flow won’t let you do this, since, while objects can be spread, other types can’t:
And there’s nothing saying T
has to be an object.
It’s pretty simple; just add a colon and the constraining type after the generic type declaration:
Constraints can be more specific, allowing more complex interactions with generic types, since they fit some criteria. For example, a generic map that uses a property of T
to determine the key:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!