Search code examples
typescriptdarttypesstructural-typingnominal-typing

typedef for Map in dart


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

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

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

What is the syntax for this?


Solution

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