TypeScript 基础语法说明
简介:TypeScript是Javascript的超集,它比Javascript有更好的维护性、面向对象等特点,可以直接编译成Javascript语法。
1.变量声明
// 给num 赋值为10,且num只能是number类型
let num: number = 10;
// 字符串型
let str: string = 'hello';
// boolean 类型
let bool: boolean = true;
// 数组
let arr: number[] = [1, 2, 3];
// 字符串样式的数组
let tuple: [string, number] = ['hello', 10];
// any表示可以定义为任何类型
let Data:any = 10
TypeScript在变量声明上给了严格的限制,并使用冒号加类型注解来为变量指定类型。
2.函数
// 创建了一个叫add的函数,形参类型限制为number
function add(num1: number, num2: number): number {
return num1 + num2;
}
const result: number = add(1, 2);
3.类
//一个叫 Person 的类,含有 name 和 age 属性
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello(): void {
console.log(`Hello, my name is ${this.name}`);
}
}
// 将实参传给构造函数
const person = new Person('John', 30);
// 调用函数方法
person.sayHello();
在TypeScript中,类是一种基于面向对象编程的抽象数据类型,它可以包含数据属性和方法。
类是一种模板,可以用来创建对象,每个对象都有自己的属性和方法,但是它们共享同一个类的属性和方法。
4.接口
// 这里定义了一个 Shape 的接口
interface Shape {
color: string;
area(): number;
}
class Circle implements Shape {
color: string;
radius: number;
constructor(color: string, radius: number) {
this.color = color;
this.radius = radius;
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle('red', 10);
console.log(circle.area());
接口是一种用于定义对象的属性和方法的规范,它描述了一个对象应该具有什么属性和方法,但并不提供实现。
接口可以用来约束函数、类和对象的结构,以保证它们的类型正确性。
5.泛型
// 使用 <T> 表示泛型类型参数 这表示这个函数可以接收任意类型的数组
function getLength<T>(arg: T[]): number {
// 在函数中,我们调用了 arg.length 来获取数组的长度,并返回这个长度。
return arg.length;
}
const arr = [1, 2, 3, 4];
const len = getLength(arr); // 返回 4
泛型是 TypeScript 中的一项强大的语言特性,可以让我们编写更加通用和灵活的代码。
通过使用泛型,我们可以创建可以适用于多种类型的函数、类和接口。
泛型可以理解为一种占位符,我们可以在定义函数或类时使用泛型来表示类型参数,从而使得代码可以适用于不同的类型。
泛型可以是任意类型,包括基本类型、对象类型、函数类型等。
**通过使用泛型,我们可以避免重复编写类似的函数,提高代码的复用性和可维护性。
同时,泛型也可以帮助我们在编译时发现类型错误,提高代码的可靠性。**