Tutorial

Flow Generic Constraints

Published on July 6, 2017
    author

    Matthew Garcia

    Flow Generic Constraints

    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.

    Where Generic Constraints are Useful

    Let’s say you have a class that wraps a Map, but makes a shallow copy before inserting:

    class ShallowMap<T> {
      map: Map<string, T>;
    
      constructor() {
        this.map = new Map();
      }
    
      get(key: string) {
        return this.map.get(key);
      }
    
      set(key: string, value: T) {
        // Make a shallow copy.  Flow will give an error on this line.
        const copy = {...value};
        this.map.set(key, copy);
      }
    }
    

    Flow won’t let you do this, since, while objects can be spread, other types can’t:

    // This works.
    const spreadEmptyObject = {...Object.create(null)};
    const spreadObjectWithProperty = {...{id: 2}};
    // This doesn't.
    const spreadNumber = {...0};
    const spreadString = {...''};
    

    And there’s nothing saying T has to be an object.

    Adding Something that Says `T` Has to Be An Object

    It’s pretty simple; just add a colon and the constraining type after the generic type declaration:

    // `T` has to be an object.
    class ShallowMap<T: Object> {
      map: Map<string, T>;
    
      constructor() {
        this.map = new Map();
      }
    
      get(key: string) {
        return this.map.get(key);
      }
    
      set(key: string, value: T) {
        // Flow is okay with this line now.
        const copy = {...value};
        this.map.set(key, copy);
      }
    }
    

    More Specific Constraints

    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:

    type Keyable = {
      key: string,
    };
    
    // `T` has a string property called `key`.
    class AutoKeyMap<T: {key: string}> {
      map: Map<string, T>;
    
      constructor() {
        this.map = new Map();
      }
    
      get(key: string) {
        return this.map.get(key);
      }
    
      set(value: T) {
        // Since `T` has a string property `key`, we can access it.
        const key = value.key;
        this.map.set(key, value);
      }
    }
    

    Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

    Learn more about our products

    About the authors
    Default avatar
    Matthew Garcia

    author

    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.

    Still looking for an answer?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    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!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Featured on Community

    Get our biweekly newsletter

    Sign up for Infrastructure as a Newsletter.

    Hollie's Hub for Good

    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

    Become a contributor

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    Welcome to the developer cloud

    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

    Learn more