Dart is an object - oriented, class - based, garbage - collected language with C - style syntax. It supports both static and dynamic typing. In Dart, everything is an object, and every object is an instance of a class.
// Variable declaration with type annotation
int age = 25;
String name = 'John';
// Class definition
class Person {
String name;
int age;
Person(this.name, this.age);
void introduce() {
print('My name is $name and I am $age years old.');
}
}
TypeScript is a statically typed superset of JavaScript. It allows developers to add types to JavaScript code, which helps catch errors during development.
// Variable declaration with type annotation
let age: number = 25;
let name: string = 'John';
// Class definition
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.`);
}
}
Dart is commonly used in Flutter development to build cross - platform mobile applications. Here is a simple example of a Flutter widget using Dart:
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('Dart in Flutter'),
),
body: Center(
child: Text('Hello, Dart!'),
),
),
);
}
}
TypeScript is widely used in web development, especially with frameworks like Angular. Here is a simple Angular component written in TypeScript:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'TypeScript in Angular';
}
In Dart, you can use try - catch
blocks to handle exceptions:
try {
int result = 10 ~/ 0;
} catch (e) {
print('An error occurred: $e');
}
In TypeScript, the try - catch
mechanism is similar to JavaScript:
try {
const result = 10 / 0;
} catch (e) {
console.log('An error occurred: ', e);
}
In Dart, you can define functions with or without type annotations:
int add(int a, int b) {
return a + b;
}
In TypeScript, type annotations are often used to make the function’s input and output clear:
function add(a: number, b: number): number {
return a + b;
}
screens
, widgets
, and models
.const
and final
keywords to create immutable objects when possible.any
type as it bypasses the type checking mechanism. Use more specific types to catch errors early.Both Dart and TypeScript bring the power of static typing to their respective ecosystems. Dart is a great choice for cross - platform mobile development with Flutter, while TypeScript shines in web development, especially with popular frameworks like Angular. By understanding the fundamental concepts, usage methods, common practices, and best practices of these two languages, developers can write more robust, maintainable, and efficient code.