Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

class Person {
  static age = 10;
}

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

like image 819
Mohan Avatar asked Sep 03 '25 03:09

Mohan


1 Answers

Answer for Dart >= v3.0.0

Dart 3 introduces Records, which allow you do what you want:

final person = (
  name: 'Foo',
  username: '@bar',
  age: 45,
  greet: () => 'Hello, Foo',
  greetIAm: (String iam) => 'Hello, Foo! I am $iam',
);

void main() {
  // Foo
  print(person.name);

  // @bar
  print(person.username);

  // 45
  print(person.age);

  // Hello Foo!
  print(person.greet());

  // Hello Foo! I am Bar!
  print(person.greetIAm('Bar!'));
}

You can also define types that declare the fields you want without the need to declare a new class:

typedef Person = ({
  String name,
  int age,
});

// With positional values instead:
typedef PersonButWithUnnamedParams = (
  String name,
  int age,
);

Person createPerson(String name, int age) {
  return (
    name: name,
    age: age,
  );
}

// Create a var direct from the type definitio.
final Person stranger = (
  age: -1,
  name: 'Stranger',
);

// Create a var of type Person through a function.
final Person stranger2 = createPerson('Stranger', -1);

// Positional params are also supported.
final PersonButWithUnnamedParams stranger3 = (
  'Stranger',
  -1,
);

Limitations:

  • You can't reference a typedef recursively, you'll need to declare a class instead.

Answer for Dart < v3.0.0

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
like image 82
lakscastro Avatar answered Sep 05 '25 01:09

lakscastro