TypeScript由浅到深(上篇)
在TypeScript中,类型系统允许我们以一种安全的方式操作数据。我们可以在编译时而不是运行时发现错误。这是通过在代码中添加类型注解来实现的。
在TypeScript中,有两种主要的类型:基本类型和复合类型。
- 基本类型:
let isDone: boolean = false;
let count: number = 10;
let name: string = "Hello, World";
- 复合类型:
let list: number[] = [1, 2, 3];
let dict: { [key: string]: any } = {
name: "Hello, World",
age: 25
};
- 函数类型:
let add = (x: number, y: number): number => {
return x + y;
};
- 类类型:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name}`;
}
}
let person: Person = new Person("Hello, World", 25);
- 接口类型:
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "Hello, World",
age: 25
};
- 泛型类型:
let identity = <T>(arg: T): T => {
return arg;
};
let result = identity<string>("Hello, World");
- 类型别名:
type Person = {
name: string;
age: number;
};
let person: Person = {
name: "Hello, World",
age: 25
};
- 类型断言:
let someValue: any = "Hello, World";
let strLength: number = (<string>someValue).length;
let anotherValue: any = "Hello, World";
let strLength: number = (someValue as string).length;
- 类型保护:
function isNumber(x: any): x is number {
return typeof x === "number";
}
let myValue: number | string = "Hello, World";
if (isNumber(myValue)) {
// 在这个块内, myValue 类型变成了 number
let numberValue: number = myValue;
}
- 类型运算符:
type A = "Hello, World";
type B = "Hello, World";
type AorB = A | B; // "Hello, World" | "Hello, World" 类型等同于 "Hello, W
评论已关闭