TypeScript(TS)- 类型定义
重点:类型定义==> 在TypeScript中,类型定义是指为变量、函数参数、函数返回值等元素指定类型的过程。它能够帮助编译器在编译时检测类型错误
-
基本类型
-
number:表示数值
-
string:表示字符串
-
boolean:表示布尔值
-
object:表示对象
-
null:表示空值
-
undefined:表示未定义
-
symbol:表示符号值
-
any:表示任意类型
let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;
let person: object = { name: "Bob", age: 30 };
let maybeNull: null = null;
let somethingUndefined: undefined = undefined;
let uniqueSymbol: symbol = Symbol("unique");
let dynamicValue: any = "dynamic";
-
自定义类型
-
TypeScript允许您创建自定义类型,例如使用接口(interfaces)来定义对象的结构,或使用类型别名(type aliases)来定义更复杂的类型结构。
interface Person {
name: string;
age: number;
}
type Point = {
x: number;
y: number;
};
-
引用定义类型
-
在TypeScript中,您可以通过声明变量时指定类型,或者通过类型断言来指定一个值的类型。还可以利用类型注解在函数参数和返回值中使用类型。
function greet(person: Person): string {
return `Hello, ${person.name}!`;
}
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
-
示例,演示了如何定义类型、引用定义类型以及类型检查:
interface Product {
id: number;
name: string;
price: number;
}
function calculateTotal(products: Product[]): number {
let total = 0;
for (const product of products) {
total += product.price;
}
return total;
}
const productsList: Product[] = [
{ id: 1, name: "Product A", price: 10 },
{ id: 2, name: "Product B", price: 20 },
];
const totalPrice: number = calculateTotal(productsList);
console.log(`Total Price: $${totalPrice}`);
在上述示例中,我们定义了一个名为 Product 的接口,表示产品的结构。然后,我们定义了一个函数 calculateTotal ,该函数接收一个 Product 类型的数组,并返回一个数值。最后,我们创建了一个产品数组 productsList ,并计算了总价格。