Dart is an object - oriented, class - based, garbage - collected language with C - style syntax. It supports interfaces, mixins, abstract classes, reified generics, and optional typing. Here is a simple Dart class example:
class Person {
String name;
int age;
Person(this.name, this.age);
void introduce() {
print('My name is $name and I am $age years old.');
}
}
void main() {
var person = Person('John', 30);
person.introduce();
}
In this example, we define a Person
class with two properties (name
and age
), a constructor, and a method (introduce
). The main
function is the entry point of a Dart program.
TypeScript is a statically typed language that compiles to plain JavaScript. It allows developers to add types to JavaScript code, which helps catch errors at compile - time. Here is a simple TypeScript class example:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`My name is ${this.name} and I am ${this.age} years old.`);
}
}
let person = new Person('John', 30);
person.introduce();
In this TypeScript code, we define a Person
class similar to the Dart example. The main difference is the explicit type annotations (string
and number
) for the properties and constructor parameters.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hello Flutter'),
),
body: Center(
child: Text('Welcome to Flutter!'),
),
),
);
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Welcome to Angular with TypeScript';
}
import
keyword. For example:import 'dart:math';
void main() {
var randomNumber = Random().nextInt(100);
print(randomNumber);
}
pub
as its package manager. You can define dependencies in the pubspec.yaml
file.// math.ts
export function add(a: number, b: number) {
return a + b;
}
// main.ts
import { add } from './math';
let result = add(5, 3);
console.log(result);
npm
(Node Package Manager) for package management. You can define dependencies in the package.json
file.Both Dart and TypeScript have their own strengths and use cases. Dart is a great choice for mobile development with Flutter and can also be used for server - side development. TypeScript is well - suited for web development, both front - end and back - end, especially when working with large - scale JavaScript applications. When choosing between Dart and TypeScript, consider the requirements of your project, the existing technology stack, and the skills of your development team.