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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With