Home > Enterprise >  typedef for Map in dart
typedef for Map in dart

Time:06-26

In TypeScript, I have a type definition for an object like below with generic:

type foo<A> = {
  val: A, 
  f: Array<((a: A) => void)>
}

Now, I want to have the same structure with dart Map with typedef.

What is the syntax for this?

CodePudding user response:

Is that it you are looking for?

typedef MyType<T> = Map<String, T>;

void main() {
  final MyType<int> foo = {'a' : 1};
  print(foo['a']);
}

CodePudding user response:

This is not possible in Dart.
From Wikipedia:
A structural type system (or property-based type system) is a major class of type systems in which type compatibility and equivalence are determined by the type's actual structure or definition and not by other characteristics such as its name or place of declaration. Structural systems are used to determine if types are equivalent and whether a type is a subtype of another.

In computer science, a type system is a nominal or nominative type system (or name-based type system) if compatibility and equivalence of data types is determined by explicit declarations and/or the name of the types. Nominal systems are used to determine if types are equivalent, as well as if a type is a subtype of another.

Typescript based on the structural type system. So, this code is possible.
Dart based on the name-based type system. So, this code is impossible.

This type alias does not refers to the existing type. It uses an anonymous type to specify type equivalence across its structure. Thus, the given Dart code cannot be compiled due to the impossibility of identifying the type.

type foo<A> = {
  val: A, 
  f: Array<((a: A) => void)>
}

P.S.

  •  Tags:  
  • dart
  • Related