TypeScript 是 JavaScript 的一个超集,并且添加了一些静态类型的特性。这使得代码的可读性和可维护性得到了提高,同时也可以在编译时发现一些错误。
以下是一些 TypeScript 的常见特性和用法的示例:
- 基本类型:
let isDone: boolean = false;
let count: number = 10;
let name: string = "Alice";
- 数组类型:
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
- 元组类型:
let x: [string, number];
x = ['hello', 10]; // OK
x = [10, 'hello']; // Error
- 枚举类型:
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
- 任意类型:
let notSure: any = 10;
notSure = "maybe a string instead";
notSure = false; // OK, but no type checking
- 空值合并运算符:
let name: string = 'Alice';
let age: number = name ? name.length : 100;
- 接口:
interface Person {
name: string;
age: number;
}
let alice: Person = {
name: 'Alice',
age: 25,
};
- 类:
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + ' ' + middleInitial + ' ' + lastName;
}
}
let user = new Student('Bob', 'M', 'Smith');
- 类型断言:
let someValue: any = 'this is a string';
let strLength: number = (<string>someValue).length;
- 泛型:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>('myString');
- 装饰器:
function readonly(target, key, descriptor) {
descriptor.writable = false;
return descriptor;
}
class MyClass {
@readonly
method() {
console.log('Method');
}
}
这些是 TypeScript 的一些基本特性和用法。在实际应用中,你可能还会使用更多的高级特性,如类型守卫、类型别名、类型断言、泛型、装饰器等。