基础类型
let str: string = "Hello, TypeScript";
let num: number = 42;
let bool: boolean = true;
定义一个接口
interface Person {
name: string;
age: number;
}
function greet(person: Person): string {
return `Hello, ${person.name}! You are ${person.age} years old.`;
}
let user: Person = { name: "John", age: 25 };
let greeting: string = greet(user);
定义一个类
class Animal {
constructor(public name: string) {}
makeSound(): string {
return "Some generic sound";
}
}
class Dog extends Animal {
makeSound(): string {
return "Woof, woof!";
}
}
let myDog: Dog = new Dog("Buddy");
let sound: string = myDog.makeSound();
简单介绍下接口和类的区别
接口不包含方法的实例化,类包含
下面用简单的例子来表示
// 接口示例
interface Shape {
area(): number;
}
// 类示例
class Circle implements Shape {
constructor(private radius: number) {}
area(): number {
return Math.PI * this.radius ** 2;
}
}
const circleInstance = new Circle(5);
console.log(circleInstance.area()); // 输出: 78.54
接口继承与类实现
interface Shape {
draw(): void;
}
class Circle implements Shape {
draw(): void {
console.log("Drawing a circle");
}
}
异步编程
function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched successfully");
}, 2000);
});
}
async function fetchDataAsync(): Promise<void> {
let data: string = await fetchData();
console.log(data);
}