TypeScript vs Dart from Tour of Heroes

This page describes how TypeScript differs from Dart. The idea is to use Angular’s Tour of Heroes tutorial example and compare language features.

Ch 2. Hero Editor

Imports

In TS you must say which object (“Component”) to import from the package. In Dart, it gets everything by default.

TypeScript

import { Component } from '@angular/core';

Dart

import 'package:angular2/core.dart';

Constructor

In TS, no constructor is required and the object is instantiated from JSON object. In Dart, the shorthand constructor can be used.

TypeScript

export class Hero {
id: number;
name: string;
}
hero: Hero = {
  id: 1,
  name: 'Windstorm'
};

Dart

class Hero {
  final int id;
  String name;
  Hero(this.id, this.name);
}
Hero hero = new Hero(1, 'Windstorm');

Multi-line String

In TypeScript, multi-line string are enclosed with single back tick (`). In Dart, multi-line string are enclosed with three single quotes (”’).

Ch 3. Master/Detail

Constants/Final Variables

In TypeScript, it’s a typed JSON structure with const keyword.

const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

In Dart, it’s a typed List with objects.

final List<Hero> mockHeroes = [
  new Hero(11, 'Mr. Nice'),
  new Hero(12, 'Narco'),
  new Hero(13, 'Bombasto'),
  new Hero(14, 'Celeritas'),
  new Hero(15, 'Magneta'),
  new Hero(16, 'RubberMan'),
  new Hero(17, 'Dynama'),
  new Hero(18, 'Dr IQ'),
  new Hero(19, 'Magma'),
  new Hero(20, 'Tornado')
];

Looping in template

Angular TypeScript and Dart look exactly the same!

<li *ngFor="let hero of heroes">
  <span class="badge">{{hero.id}}</span> {{hero.name}}
</li>

Constant Array/List

Dart uses const keyword in front of the list declaration. TypeScript doesn’t do that.

styles: const [
  '''
  .selected {
    background-color: #CFD8DC !important;
    color: white;
  }
...

Angular Event Binding

TypeScript and Dart version are exactly the same here:

<li *ngFor="let hero of heroes" (click)="onSelect(hero)">
  <span class="badge">{{hero.id}}</span> {{hero.name}}
</li>

Event Handler

TypeScript definition looks quite normal:

onSelect(hero: Hero): void {
  this.selectedHero = hero;
}

Dart version is slightly cleaner as the return type of “void” isn’t required. Also, “this” keyword isn’t needed as it’s already in the object’s method, not constructor.

onSelect(Hero hero) {
  selectedHero = hero;
}
This entry was posted in General, Programming. Bookmark the permalink.

Leave a Reply