【TypeScript】TS 看这一篇就够了
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 logClass(target) {
target.isLogged = true;
}
@logClass
class MyClass {
// ...
}
- 异步函数:
async function asyncFunction(): Promise<string> {
return "Hello, world!";
}
asyncFunction().then(value => console.log(value));
这些是 TypeScript 的基本特性,实际项目中可能会用到更多高级特性,如泛型、类型守卫、类型别名等。
评论已关闭