在 TypeScript 中,冒号 :
通常用于类型注解,用来明确指定变量、函数参数、函数返回值等的类型。
1. 变量声明:
const myNumber: number = 42;
const myString: string = "Hello, TypeScript";
在这里,冒号后面的部分是类型注解,指定了变量的类型。
2. 函数参数和返回值:
function add(num1: number, num2: number): number {
return num1 + num2;
}
在函数参数和返回值上,冒号同样用于类型注解。上述例子中,num1
和 num2
被注解为 number
类型,而函数的返回值被注解为 number
。
3. 对象和接口:
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30
};
在对象字面量和接口中,冒号也用于指定键值对中值的类型。
总的来说,冒号在 TypeScript 中主要是用于类型注解,有助于静态类型检查和代码可读性。