Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Run into such thing lately, a function declaration:

static required(control: AbstractControl): {
  [key: string]: boolean;

What is this return value? An object with an arbitrary amount of properties, where each of them is a boolean and has a name, which appears to be a string? It's more of a typescript question I guess, but just in case someone wonders where I found that - it's Angular's Validators class.

It might be better idea to abandon now {[key: K]: T} construction but use JavaScript built-in Map? – taro Jan 16, 2021 at 17:36

This is a key/value structure, named index signatures (or previously known as indexable Types) in typescript.

The key is a string and the value is a boolean. For example:

let map : { [key: string]: boolean} = {};
map["foo"] = true;
map["bar"] = false;
map.foo = true;
map["foobar"] = "foo"; // Throws exception
map[1] = true; // Curiously doesn't throws exception

Check this sample on the Typescript Playground.

@lonewarrior556 The code "map.foo = true" actually doesn't throw an exception. The original answer claimed that it did, but that was incorrect, and the answer has been udated accordingly. The TypeScript Playground link, however, still includes the erroneous comment. – colin moock Aug 15, 2020 at 16:48 Ran into a similar bit of code, where one of the logic branches returns null, but the return type is {[key: string]: boolean} and it tells me null is not assignable to this type. Maybe I have strict null type checking on and hte sample doesn't? I don't know what to make my return type so it works. – Marz Nov 30, 2021 at 22:14

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.