Typescript是JavaScript的超集,它扩展了JS的语法,新增了一些新的特性,主要区别如下:
1.类型注解与静态类型检查
ts支持静态类型系统,可以为变量、函数的参数和返回值指定类型。
let isDone: boolean = false;
function add(x: number, y: number): number {
return x + y;
}
2.接口(interface)
ts提供了接口,用于描述对象必须提供的属性或方法。
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
console.log("Hello, " + person.name);
}
3.类型别名
ts可以创建类型别名
type Point = {
x: number;
y: number;
}
4.枚举类型(Enums)
ts提供了枚举类型,为一组数字赋予有意义的名称。
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
5.泛型(Generics)
ts支持泛型,即在定义函数、接口或类的时候不预先指定具体类型,在使用的时候指定类型。
function indentity<T>(arg: T): T {
return arg;
}
6.装饰器
ts支持装饰器,语法形式类似Python。js目前暂不支持装饰器,据说装饰器提案已经在ECMAScript提案阶段。
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class Greeter {
greeting string;
}
7.模块化
虽然ES6(ES2015)及以后的版本支持模块化,Ts也提供了对模块化的支持,并在早期就支持了模块化的概念。
ts模块化使用的标准是ESModule。
import {Component} from '@/angular/core'
8.命名空间
ts提供了命名空间支持,用于组织代码和解决命名冲突。
namespace Validation {
export interface {
isAcceptable(s: string): boolean;
}
}
9.非空断言操作符
ts提供了非空断言操作符(!),用于告诉ts编译器某个值一定不是null或者undefined.
function liveDangerousely(x?: number | null) {
//不会报错
console.log(x!.toFixed());
}
总结:
TypeScript主要目标是提供静态类型检查和最新的JavaScript特性,他可以编译成纯净的JavaScript代码。这些类型系统的特性使得TypeScript在大型项目或者需要更多开发工具支持的场景中很有用,而JavaScript则适合不需要额外类型系统支持的情况。随着JavaScript语言本身的发展,一些新特性(如模块化、async/await)已经被添加到JavaScript中,但TypeScript仍然在类型安全性和其他语言特性方面提供了更多的功能。