Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a Map containing certain properties with flowtype & immutable.js

Given a website object created like this

import {Map} from 'immutable' 
const website = new Map({name: 'My Website', url: 'http://www.myw.fr'})

How could I declare a websiteType which would be a map containing exactly the given properties. I know I can do:

declare type websiteType = Map<string,string>

But I would like to be more specific, and declare a map that must contain the properties name and url of type string.

Is it even possible?

like image 844
Nihau Avatar asked May 16 '16 12:05

Nihau


1 Answers

Hopefully I got your question right, because I have never used a map from "immutable" therefore I will use an es6 Map.

Why don't you just use a class?

class Website extends Map<string, string> {
    constructor(name: string, url: string) {
        super()
        this.set("name", name)
        this.set("url", url)
    }
}

That way you can initialize it like this:

const website = new Website("awesome", "www.awesome.com")

and then perform get and set operations.

If you miss the parameters flowtype will throw an error.

I hope this will be a solution for you.

EDIT:

You could also just create a function which initializes your map.

declare type WebsiteType = Map<string, string>

function createWebsite(name: string, description: string) {
    const website: WebsiteType = new Map
    website.set("name", name)
    website.set("description", description)
    return website
}

However I find the first solution nicer because it gives you a Website type and you don't have to create a creator function.

EDIT:

If you want the same syntax like you used the map initialization, you could also do:

class Website extends Map<string, string> {
    constructor({name, url, ...rest}) {
        super()
        this.set("name", name)
        this.set("url", url)
        for(const name in rest) {
            this.set(name, rest[name])
        }
    }
}

However I think the first one meaningful.

like image 147
Arwed Mett Avatar answered Nov 05 '22 07:11

Arwed Mett