- npm i typescript -g进行安装;
- javascript是弱类型脚本语言,不利于后期代码维护;
- 类型注解
let str:string; - 类型断言
let numArr = [1, 2, 3]; const result = numArr.find(item => item > 2) as number; - 联合类型
let str:string | null = null; let num:1|2|3 = 2; - 数组声明方式:(1)
let arr:number[] = [1,2,3];(2)let arr:Array<string> = ['a','b','c']; - 元组:限制存储的数据个数及每个数据的类型
let arr:[number,string,number?] =[1,'a'] - 枚举
enum MyEnum {
A,
B,
C
}
console.log(MyEnum.A);
console.log(MyEnum[0]);
- void 0 获取undefined,void表示空值,在函数中使用表示没有返回值;
- 函数中的类型注解,必选参数放左边,可选参数放右边,如果没有返回值使用void;
function MyFun(a:number,b?:string,...rest:number[]):number{
return 100;
}
function MyFun2(a:number,b?:string):void{
}
- 接口,TypeScript 中的
interface是用来定义对象的形状(shape)或结构(structure)的语法元素。
interface Person {
firstName: string;
lastName: string;
age?: number; // 可选属性
}
function greet(person: Person) {
console.log(`Hello, ${person.firstName} ${person.lastName}!`);
}
const john: Person = {
firstName: "John",
lastName: "Doe",
age: 30,
};
greet(john);
描述函数类型
interface MathFunction {
(x: number, y: number): number;
}
const add: MathFunction = (a, b) => a + b;
描述类的结构
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Woof!");
}
}
注:接口用于定义结构和约定,而类用于创建对象和实现行为。
- 类型别名
type MyType = string | number; let a: MyType = 10; - 泛型
function identity<T>(arg: T): T {
return arg;
}
let result = identity<string>("Hello, TypeScript");
- 泛型约束,以下示例中
T被约束为具有length属性的类型,以确保在函数中可以安全地访问length属性。
function logLength<T extends { length: number }>(arg: T): void {
console.log(arg.length);
}
logLength("Hello"); // 合法
logLength(42); // 报错,因为数字没有 length 属性