Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dart equivalent of anonymous type object from TypeScript

In TypeScript, I can simply define an anonymous object like below and still get intellisense for it.

let person = {
  age: 10,
}

Unfortunately, I cannot able to do that same in the dart lang.

But I can do something similar using class and static properties.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Person {
  static age = 10;
}

This gets the job done but I wonder if there are any simpler approach for this.

>Solution :

You can’t.

Dart doesn’t have such thing because it’s strongly typed.

You can define a Map:

final person = <String, int>{'age': 10};

But in the intellisense perspective it is only a Map which contains keys of type String and values of type int, can’t infer that there’s a key age of value 10

So you should define it as a class if you want intellisense:

class Person {
  const Person(this.age);

  final int age;
}

const person = Person(10);

print(person.age); // 10
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading