Examples for Dart code compared to TypeScript code.
You can easily try all Dart examples on https://dartpad.dartlang.org/ and TypeScript examples on http://www.typescriptlang.org/play/
package.json // NPM
pubspec.yaml // Pub
// single line comment
/*
multi line comment
*/
// single line comment
//
// multi line comment
//
/// documentation comment
console.log('TypeScript code');
print('Dart code');
const boolType: boolean = true;
const numberType: number = 5;
const stringType: string = 'John';
const arrayType: [] = [];
const anyType: any = 'John'; // Can be anything;
const tupleType: [string, number] = ['John', 5];
final bool boolType = true;
final int numberType = 5;
final double doubleType = 5.5;
final String stringType = 'John';
final List listType = [];
final dynamic dynamicType = 'John'; // Can be anything;
var a: string = 'a';
let b: string = 'b';
const c: string = 'c';
var a = 'a';
-
final String c = 'c'; // runtime constant
const c = 'c'; // compile time constant / freezing
const firstName: string = 'John';
const lastName: string = 'Doe';
console.log(`This is ${firstName} ${lastName})
final String firstName = 'John';
final String lastName = 'Doe';
print('This is $firstName $lastName');
const persons: string[] = ['John', 'William'];
final List<String> persons = ['John', 'William'];
const person = {
name: 'John',
};
console.log(person.name) // John
// As a map
Map person = {
'name': 'John'
}
print(person['name']) // John
// As a class
class Person {
String name = 'John';
}
var person = Person();
print(person.name) // John
function add(a: number, b: number): number {
return a + b;
}
int add(int a, int b) {
return a + b;
}
async function add(a: number, b: number): number {
return a + b;
}
Future<int> add(int a, int b) async {
return a + b;
}
export class Foo {}
class Foo extends StatelessWidget {}
class Foo extends StatefulWidget {}
export class Foo {
person: string;
constructor(name) {
this.person = name;
}
}
class Foo {
String person;
Foo({ this.person })
}
export class Foo {
constructor() {
super()
}
}
class Foo {
Foo({Key key}) : super(key:key);
}
const person = {
name: "John Doe"
}
// stringify
const personJson = JSON.stringify(person);
console.log(personJson); // '{ "name": "John Doe", "age": 33 }'
// parse
const personObject = JSON.parse('{ "name": "John Doe", "age": 33 }');
console.log(personObject.name) // John Doe
import 'dart:convert';
Map person = {
"name": "John Doe"
};
// stringify
var personJson = jsonEncode(person);
print(personJson); // '{ "name": "John Doe", "age": 33 }'
// parse
Map personMap = jsonDecode('{ "name": "John Doe", "age": 33 }');
print(personMap["name"]) // John Doe