来自 TypeScript 的匿名类型对象的 Dart 等价物

Dart equivalent of anonymous type object from TypeScript

在 TypeScript 中,我可以像下面这样简单地定义一个匿名对象,并且仍然可以获得它的智能感知。

let person = {
  age: 10,
}

不幸的是,我不能在飞镖语言中做同样的事情。

但我可以使用 class 和静态属性做类似的事情。

class Person {
  static age = 10;
}

这样就完成了工作,但我想知道是否有任何更简单的方法。

你不能。

Dart 不支持匿名类型。

你可以定义一个Map:

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

但在智能感知中它只是一个 Map 包含 String 类型的键和 int 类型的值,不能推断有一个键 [=16] =] 的价值 10

所以如果你想要智能感知,你应该将它定义为 class:

class Person {
  const Person(this.age);

  final int age;
}

const person = Person(10);

print(person.age); // 10