ts使用语法规则

TypeScript(TS)的语法规则主要继承了JavaScript,但由于其提供了静态类型检查以及更丰富的面向对象编程特性,因此在使用上也有一些独特之处。以下是一些TypeScript的基本语法规则:

  1. 变量声明

    TypeScript使用letconstvar来声明变量。其中,letconst是ES6中引入的,提供了块级作用域。const声明的变量是只读的,一旦赋值后就不能再改变。

复制代码

typescript复制代码

|---|----------------------------|
| | let num: number = 10; |
| | const PI: number = 3.14; |

  1. 类型注解

    TypeScript中,可以通过在变量名或函数参数名后面添加冒号:和类型名称来进行类型注解。这有助于在编译时进行类型检查。

复制代码

typescript复制代码

|---|-----------------------------------|
| | let isDone: boolean = false; |
| | let age: number = 25; |
| | let firstName: string = "John"; |

  1. 接口

    接口用于定义对象的类型。它描述了对象应该具有的形状。

复制代码

typescript复制代码

|---|---------------------------------------------------|
| | interface Person { |
| | name: string; |
| | age: number; |
| | greet(): void; |
| | } |
| | |
| | let person: Person = { |
| | name: "Alice", |
| | age: 20, |
| | greet() { |
| | console.log("Hello, my name is " + this.name); |
| | } |
| | }; |

  1. TypeScript支持基于类的面向对象编程。类定义了对象的属性和方法。

复制代码

typescript复制代码

|---|---------------------------------------------------|
| | class Animal { |
| | name: string; |
| | |
| | constructor(name: string) { |
| | this.name = name; |
| | } |
| | |
| | move(): void { |
| | console.log(`${this.name} moves a little.`); |
| | } |
| | } |

  1. 函数

    TypeScript中的函数可以使用类型注解来指定参数和返回值的类型。

复制代码

typescript复制代码

|---|-------------------------------------------|
| | function greet(name: string): string { |
| | return "Hello, " + name; |
| | } |

  1. 访问修饰符

    TypeScript支持使用publicprivateprotected访问修饰符来限制类成员的可访问性。

  2. 枚举

    枚举类型用于定义数值集合。

复制代码

typescript复制代码

|---|------------------------------------|
| | enum Color { Red, Green, Blue } |
| | let c: Color = Color.Green; |

  1. 泛型
    泛型允许在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型。
  2. 三元运算符和条件(三元)类型
    TypeScript 也支持三元运算符,并允许基于条件的类型推断。
  3. 装饰器
    装饰器是一种特殊类型的声明,它可以被附加到类声明,方法,访问符,属性或参数上。装饰器使用@表达式,后面跟一个装饰器函数。
相关推荐
天下无贼!14 小时前
2024年最新版TypeScript学习笔记——泛型、接口、枚举、自定义类型等知识点
前端·javascript·vue.js·笔记·学习·typescript·html
Jorah3 天前
1. TypeScript基本语法
javascript·ubuntu·typescript
小白小白从不日白3 天前
TS axios封装
前端·typescript
aimmon4 天前
Superset二次开发之源码DependencyList.tsx 分析
前端·typescript·二次开发·bi·superset
下雪天的夏风4 天前
Vant 按需引入导致 Typescript,eslint 报错问题
前端·typescript·eslint
theMuseCatcher5 天前
Vue3+TypeScript+Vite+Less 开发 H5 项目(amfe-flexible + postcss-pxtorem)
typescript·less·postcss
Qiyandays5 天前
vue + Lodop 制作可视化设计页面 实现打印设计功能(四)
前端·vue.js·typescript
人工智能的苟富贵5 天前
微信小程序中的模块化、组件化开发:完整指南
微信小程序·小程序·typescript
Code blocks7 天前
小试牛刀-区块链Solana多签账户
算法·typescript·区块链·github
shiming88798 天前
Vue 生命周期与 TypeScript:深入理解组件生命周期
前端·vue.js·typescript