22

How do I give a new name to already existing type?

Let's say I want to give to a List<String> the name Directives and then be able to say directives = new Directives().

user7610
  • 25,267
  • 15
  • 124
  • 150
  • you don't, you cannot instantiate one type to another – Mo Patel Nov 03 '13 at 16:50
  • @MPatel You misunderstood me. I want to do a C++ style typedef. That should be somehow possible, yes? I can always embed the List in a new Directives class, but then exporting all the methods on the List is a lot of work… – user7610 Nov 03 '13 at 16:53
  • Duplicates http://stackoverflow.com/questions/16247045/how-do-i-extend-a-list-in-dart http://stackoverflow.com/questions/18459181/extending-base-list-class-with-extra-functionality-in-dart-language – user7610 Nov 19 '13 at 23:23
  • 1
    https://github.com/dart-lang/sdk/blob/master/docs/language/informal/generic-function-type-alias.md – Arto Bendiken Mar 27 '18 at 12:33

2 Answers2

33

It is possible now via an empty mixin

mixin ToAlias{}

class Stuff<T> {
  T value;
  Stuff(this.value);
}

class StuffInt = Stuff<int> with ToAlias;

main() {
  var stuffInt = StuffInt(3);
}

EDIT 2.13

It looks likely that unreleased 2.13 will contain proper type aliasing without the need of a mixin.

typedef IntList = List<int>;
IntList il = [1,2,3];

https://github.com/dart-lang/language/issues/65#issuecomment-809900008 https://medium.com/dartlang/announcing-dart-2-12-499a6e689c87

atreeon
  • 21,799
  • 13
  • 85
  • 104
11

You can't define alias. For your case you can use DelegatingList from quiver to define Directives :

import 'package:quiver/collection.dart';

class Directives extends DelegatingList<String> {
  final List<String> delegate = [];
}
Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
  • 7
    Strange. I would have thought that the Dart people would encourage giving names to data structures. There is a typedef keyword in Dart but that works only for function signatures. Thanks for your answer. – user7610 Nov 04 '13 at 11:03