TypeScript 的核心知识点合集
在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 = 4;
notSure = "maybe a string instead";
notSure = false; // OK, but no type checking
- 空值(用于标识变量可能没有值):
let u: undefined = undefined;
let n: null = null;
- 函数类型:
let add = (x: number, y: number): number => {
return x + y;
};
- 类类型:
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
return 'Hello, ' + this.name;
}
}
let person: Person = new Person('Alice');
- 接口类型(用于定义对象的形状):
interface Person {
name: string;
age?: number; // 可选属性
}
let person: Person = {
name: 'Alice',
age: 30,
};
- 类型别名(为类型定义别名):
type Name = string;
type Point = { x: number; y: number };
let name: Name = 'Alice';
let point: Point = { x: 10, y: 20 };
- 类型断言(当你确定一个变量的类型):
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'); // type of output will be 'string'
这些是TypeScript中的核心概念,能够帮助开发者理解和使用这个强大的类型系统。
评论已关闭