Suppose I have a function that needs to return something of type StringMap<string, boolean>
. An example return that is valid is: {"required": true}
.
Now, I've read in a tutorial (it's not important which tutorial) you can create a function that has return type of { [s: string]: boolean }
and this is the same return type as the StringMap above.
I don't understand how are these two the same return type? And how the second version is even valid?
function (): number {}
. In our second version we use s: string
which means we give the variable a name, and specify it's type, how are we suddenly allowed to give the variable the name s
?[s: string]
as the key in the second version (therefore the key is now an array). While a StringMap has a string as the key.The syntax is a bit different than you think. It's a unique syntax for defining dictionaries\maps.
{ [s: string]: boolean }
means: a map, which has a key with type string, and it's values are boolean. The s
means nothing at all, it could have been anything you want.
(Then why give it a name in the first place? my guess is to make the code more clear, when mapping more complex types. Sometimes you'll want to call the index id
, sometimes address
, etc..)
More info here, indexed types is what you want.
The Typescript handbook online isn't the most friendly documentation ever, but I think it's good enough and I recommend everyone who uses typescript to at least skim through it. Especially since in 2.0+ they added a bunch of crazy\awesome type features like mapped types.
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