Home > Mobile >  Dart equivalent of anonymous type object from TypeScript
Dart equivalent of anonymous type object from TypeScript

Time:05-09

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.

class Person {
  static age = 10;
}

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

CodePudding user response:

You can't.

Dart doesn't support anonymous types.

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
  • Related