TypeScript快速上手,class,public,private,extends

这篇博客介绍了TypeScript的基础语法,包括如何使用class定义类,理解public和private访问修饰符,以及如何实现类的继承。通过示例代码展示了类型注解、构造函数、方法的使用,并解释了错误提示的原因。同时,文章还探讨了extends关键字在继承中的应用,以及如何重写和调用父类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TypeScript快速上手,class,public,private,extends

运行快速上手

在windows终端cmd命令行以管理员身份运行,输入cnpm install -g typescript进行安装,记得将cnpm下载源切换到淘宝镜像源。然后继续输入tsc -v查看是否安装成功。出现版本号即表示安装成功。
在这里插入图片描述

类型批注

TypeScript 通过类型批注提供静态类型以在编译时启动类型检查。这是可选的,而且可以被忽略而使用 JavaScript 常规的动态类型。

function Add(left: number, right: number): number {
   
   
    return left + right;
}

对于基本类型的批注是number, bool和string。而弱或动态类型的结构则是any类型。当类型没有给出时,TypeScript编译器利用类型推断以推断类型。如果由于缺乏声明,没有类型可以被推断出,那么它就会默认为是动态的any类型。

class说明

TypeScript支持集成了可选的类型批注支持的ECMAScript 6的类。以下是定义一个类的代码。

class Shape {
   
   
    area: number;
    color: string;
    constructor ( name: string, width: number, height: number ) {
   
   
        this.area = width * height;
        this.color = "pink";
    };
    shoutout() {
   
   
        return "I'm " + this.color + " " + this.name +  " with an area of " + this.area + " cm squared.";
    }
}
var square = new Shape("square", 30, 30);
console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Name of Shape: ' + square.name );
console.log( 'Color of Shape: ' + square.color )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值