TypeScript是JavaScript的一个超集,并且在JavaScript的基础上添加了一些额外的功能,比如类型注解和类型检查。这使得开发者可以在开发过程中捕捉到一些错误,而不是在运行时才发现。
以下是TypeScript的一些关键概念和语法的概要:
- 类型注解:
let count: number = 10;
let name: string = "John";
let isDone: boolean = false;
- 接口:
interface Person {
name: string;
age: number;
}
let john: Person = { name: "John", age: 30 };
- 类:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let john = new Person("John", 30);
- 类型别名:
type Person = {
name: string;
age: number;
};
let john: Person = { name: "John", age: 30 };
- 泛型:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello World");
- 函数:
function add(x: number, y: number): number {
return x + y;
}
let result = add(1, 2);
- 箭头函数:
let multiply = (x: number, y: number): number => {
return x * y;
};
let result = multiply(2, 3);
- 类型断言:
let someValue: any = "this is a string";
let stringLength: number = (<string>someValue).length;
- 异步函数:
async function getJson(): Promise<any> {
let response = await fetch("http://example.com/data.json");
return response.json();
}
getJson().then(data => console.log(data));
- 修饰符:
class MyClass {
private myNumber: number = 5;
static myString: string = "Hello World";
constructor() {
this.myNumber = 10;
}
static myFunction() {
return MyClass.myString;
}
}
- 枚举:
enum Color {
Red = 1,
Green = 2,
Blue = 4
}
let colorName: string = Color[2];
- 命名空间:
namespace Shapes {
export class Triangle { /* ... */ }
export class Square { /* ... */ }
}
let mySquare = new Shapes.Square();
- Decorators(装饰器):
function logClass(constructor: Function) {
console.log(co