TypeScript 输入输出

TypeScript 是一种由微软开发的开源编程语言,它是 JavaScript 的一个超集,添加了可选的静态类型和基于类的面向对象编程,TypeScript 的设计目标是提高代码的可读性和可维护性,同时保持对 JavaScript 的兼容性,在许多方面,TypeScript 都可以被视为是 JavaScript 的一个更好的版本。

TypeScript 输入输出
(图片来源网络,侵删)

TypeScript 基础

安装 TypeScript

要开始使用 TypeScript,首先需要在计算机上安装它,可以通过 Node.js 包管理器 npm 来安装 TypeScript:

npm install g typescript

TypeScript 文件

创建一个名为 example.ts 的文件,然后在其中输入以下内容:

function greeter(person: string) {
    return "Hello, " + person;
}
let user = "TypeScript User";
console.log(greeter(user));

这个文件定义了一个名为 greeter 的函数,该函数接受一个字符串参数 person,并返回一个问候语,我们创建了一个名为 user 的变量,并将其值设置为 "TypeScript User",我们调用 greeter 函数并将结果打印到控制台。

编译 TypeScript 文件

要编译 TypeScript 文件,需要使用 tsc 命令:

tsc example.ts

这将生成一个名为 example.js 的 JavaScript 文件,可以使用 Node.js 来运行此文件:

node example.js

输出应该是:

Hello, TypeScript User

TypeScript 特性

类型注解

TypeScript 支持两种类型的注解:尖括号(<>)和方括号([]),尖括号表示具体的类型,而方括号表示任意类型。

let numbers: number[] = [1, 2, 3]; // 数组中的所有元素都是数字类型
let strings: string[] = ["TypeScript", "Rocks"]; // 同上
let mixed: (number | string)[] = [1, "two", 3, "four"]; // 混合类型数组,可以包含数字和字符串类型

接口

接口是一种描述对象结构的方式,它们可以用来检查一个对象是否具有特定的属性和方法。

interface Person {
    firstName: string;
    lastName: string;
}
function greeter(person: Person): void {
    console.log("Hello, " + person.firstName + " " + person.lastName);
}

类和对象继承

TypeScript 支持类和对象继承。

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    move(distanceInMeters: number = 0) {
        console.log(${this.name} moved ${distanceInMeters}m.);
    }
}
class Dog extends Animal {
    bark() {
        console.log("Woof!");
    }
}
const dog = new Dog("Rufus");
dog.bark(); // Woof!
dog.move(10); // Rufus moved 10m. without specifying distance in meters. default value is used. and then the method of the parent class is called. which prints the output as mentioned above. but if we call the move method with a distance, it will be called from the Dog class and not from the Animal class. because of the way JavaScript works with classes and objects. and that's why we need to use the super keyword to call the method from the parent class. like this: dog.super.move(10); // Rufus moved 10m. which is the expected output. and now we have achieved our goal of calling the method from the parent class when needed. even though we are using an ES6 class syntax. which is similar to TypeScript classes. but they are not exactly the same thing. and there are some differences between them as well. which we will discuss later in this tutorial. on advanced topics section. where we will cover more complex topics related to TypeScript and its features. such as decorators, modules, async/await, etc...

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/475576.html

(0)
未希新媒体运营
上一篇 2024-04-15 00:22
下一篇 2024-04-15 00:23

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入