Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Object (with specific key, value types) from function in TypeScript

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?

  1. All the return types I have seen in TypeScript have only included the type in the past i.e. boolean, number, any. For example 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?
  2. On top of that we put this string inside an array [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.
like image 983
Arshaan Avatar asked Jan 05 '23 14:01

Arshaan


1 Answers

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.

like image 132
Aviad Hadad Avatar answered Jan 14 '23 06:01

Aviad Hadad