数据类型:原始类型:数字(Number)、字符串(String)、布尔值(Boolean)、空(null)、未定义(undefined)、布尔值(Boolean)、字符串(String)、Symbol(符号)、BigInt(大整数)
1.声明变量: 使用let或const关键字声明变量,并可选择指定类型
let name: string = 'John'; // 字符串类型 const age: number = 25; // 数字类型
2.函数声明: 使用箭头函数(=>)或function关键字来声明函数,并可以指定参数类型和返回值类型。
const add = (a: number, b: number): number => { return a + b; } function greet(name: string): void { console.log(`Hello, ${name}!`); }
3.接口: 使用接口定义对象的结构和类型。
interface Person { name: string; age: number; } const person: Person = { name: 'John', age: 25 };
4.类: 使用class关键字定义类,并可以定义属性和方法。
class Animal { name: string; constructor(name: string) { this.name = name; } sayHello(): void { console.log(`Hello, I'm ${this.name}.`); } } const cat = new Animal('Whiskers'); cat.sayHello(); // 输出: Hello, I'm Whiskers.
5.数组: 使用数组类型加上元素类型声明一个数组。
const numbers: number[] = [1, 2, 3, 4, 5]; const names: string[] = ['John', 'Jane', 'Bob'];
6.类型推断: TypeScript会根据上下文自动推断类型,不需要手动指定。
const message = 'Hello'; // 推断为string类型 const count = 10; // 推断为number类型 function multiply(a: number, b: number) { return a * b; // 推断返回值为number类型 }
7.条件语句:
let x: number = 10; if (x > 0) { console.log('x is positive'); } else { console.log('x is not positive'); }