现在知道了 .ts 文件是不可以直接执行的,需要转换成 .js 文件,才能够进行运行,现在开始尝试:

  1. # npm 全局安装 TypeScript
  2. $ npm install typescript -g
  3. # 将ts文件转换成js文件
  4. $ ts demo.ts
  5. # 通过node 运行js文件
  6. $ node demo.js

上方的例子分为了两步(先转换在运行),可以通过npm(ts-node),来进行合并操作:

  1. $ npm install ts-node -g
  2. # 直接进行运行
  3. $ ts-node demo.ts

静态类型的深度理解

  1. /** count
  2. * 不可以为其他类型
  3. * 编辑器会提示数字类型的所有方法
  4. */
  5. const count: number = 2021

基础类型和对象类型

基础类型:boolean, number, string, void, undefined, symbol, null
对象类型:{}, Class, function, []

  1. // 对象类型
  2. class Person { }
  3. const teacher: {
  4. name: string,
  5. age: number
  6. } = {
  7. name: 'Zws',
  8. age: 18
  9. }
  10. const numbers: number[] = [1, 2, 3]
  11. const zws: Person = new Person()
  12. // 对象类型-函数的两种写法儿
  13. // 第一种(可以忽略 number,类型推断会推断出返回值是number)
  14. const func = (str: string): number => {
  15. return parseInt(str, 10)
  16. }
  17. // 第二种(可以理解为:冒号后面跟的是函数的类型,等号后面是函数体。不能忽略number,不然语法错误)
  18. const func1: (str: string) => number = (str) => {
  19. return parseInt(str, 10)
  20. }

类型注解和类型推断

类型推断(type inference):TS 会自动的去尝试分析变量的类型。例如:

  1. // 这就是典型的类型推断,它们的类型是 number 而且值永远都不会变的
  2. const firstnumber = 1;
  3. const secondNumber = 2;
  4. const total = firstNumber + secondNumber;

类型注解(type annotation) :告诉 TS 变量是什么类型。例如:

  1. // 当 TS 无法推断出变量类型的时候需要添加类型注解
  2. function getTotal (firstNumber: number, secondNumber: number) {
  3. return firstNumber + secondNumber
  4. }
  5. const total = getTotal(1, 2)
  6. // 其他的情况
  7. interface Person {
  8. name: string
  9. }
  10. const rawData = '{"name": "zws"}'
  11. const newData: Person = JSON.parse(rawData)
  12. // 一个变量是一个数字类型,后续要变成字符串。类似或运算符
  13. let temp: number | string = 123;
  14. temp = '456'

函数相关类型

  1. // void类型:没有返回值
  2. function sayHello (): void {
  3. console.log('hello');
  4. }
  5. // never类型:函数执行不完
  6. function errorEmitter(): never {
  7. while (true){}
  8. }
  9. // 函数的解构赋值
  10. function add ({ first, second }: { first: number, second: number }): number {
  11. return first + second
  12. }
  13. add({ first: 1, second: 2 })

数组和元组

数组

  1. // 数组可以是数字和字符串类型
  2. const numberArr: (string | number)[] = [1, 2, 3]
  3. // undefined 数组
  4. const undefinedArr: undefined[] = [undefined, undefined, undefined]
  5. // 存储对象类型的内容
  6. const objectArr: { name: string, age: number }[] = [{
  7. name: 'zws',
  8. age: 18
  9. }]
  10. // 使用类型别名(type alias)
  11. type User = { name: string, age: number }
  12. // 存储对象类型的内容
  13. const objectArr: User[] = [{
  14. name: 'zws',
  15. age: 18
  16. }]
  17. // 关于 Class
  18. class Teacher {
  19. name: string;
  20. age: number;
  21. }
  22. const objectArr: Teacher[] = [
  23. new Teacher(),
  24. {
  25. name: 'zws',
  26. age: 18
  27. }
  28. ]

元组 tuple

数组长度和类型都固定的情况下,可以使用元组进行管理

  1. const teacherInfo: [string, string, number] = ['zws', 'jon', 18]
  2. const teacherList: [string, string, number][] = [
  3. ['zws', 'jon', 18],
  4. ['sun', 'dea', 22],
  5. ['za2', 'wall', 26]
  6. ]

Interface 接口

关于Interface代码
interface 和 type 相类似,但不完全一致。type 可以校验基础类型。而 Interface 不支持基础类型的校验。TS 里,能使用Interface的话就使用Interface

关于 interface:

  • 接口只是 TS 帮助我们校验的工具,并不会变成 JS
  • 属性前加上?,代表该变量可有可无
  • 属性前加上readonly,代表只读不可修改 ```typescript interface Pereson { name: string age?: number readonly test: string } const getPersonName = (person: Pereson) => { console.log(person.name) }

const setPersonName = (person: Pereson, name: string): void => { person.name = name }

const person = { name: ‘zws’, age: 18, sex: ‘male’, }

getPersonName(person) setPersonName(person, ‘lin’)

  1. - 如果以字面量的形式传给函数,TS 会进行强校验。例如:<br />
  2. ```typescript
  3. interface Pereson {
  4. name: string
  5. age?: number
  6. }
  7. const getPersonName = (person: Pereson) => {
  8. console.log(person.name)
  9. }
  10. const setPersonName = (person: Pereson, name: string): void => {
  11. person.name = name
  12. }
  13. const person = {
  14. name: 'zws',
  15. age: 18,
  16. sex: 'male',
  17. }
  18. getPersonName({
  19. name: 'zws',
  20. age: 18,
  21. sex: 'male'
  22. }) // 会报错,sex不在 Person 种
  23. setPersonName(person, 'lin')
  24. // 修改 Interface 解决(最后一行代表的是,可以是任何字符串类型的键,任何值)
  25. interface Pereson {
  26. name: string
  27. age?: number
  28. [propName: string]: any
  29. }
  • Interface 里支持方法的写入

    1. interface Pereson {
    2. name: string
    3. age?: number
    4. say(): string
    5. }
    6. const person = {
    7. name: 'zws',
    8. say() {
    9. return 'say hello'
    10. }
    11. }
  • class类应用接口

    1. interface Pereson {
    2. name: string
    3. age?: number
    4. say(): string
    5. }
    6. // 语法 implements
    7. class User implements Pereson {
    8. name = 'zws'
    9. say() {
    10. return 'say hello'
    11. }
    12. }
  • 接口之间互相继承

    1. // 关键字 extends
    2. interface Teacher extends Pereson {}
  • 接口定义函数

    1. interface SayHi {
    2. (word: string): string
    3. }
    4. const say: SayHi = (word: string) => {
    5. return word
    6. }

    使用 interface 实现公用

    1. interface Person {
    2. name: string
    3. }
    4. interface Teacher extends Person {}
    5. interface Student extends Person {
    6. age: number
    7. }
    8. const teacher = {
    9. name: 'zws'
    10. }
    11. const student = {
    12. name: 'has',
    13. age: 18
    14. }
    15. const getUserInfo = (user: Person) => {
    16. console.log(user.name)
    17. }
    18. getUserInfo(teacher)
    19. getUserInfo(student)

    class-类

    类的定义与继承

    关于类的定义与继承代码 ```typescript // 类里写属性与方法 class Person { name = ‘zws’ getName() { return this.name } } const person = new Person() console.log(person.getName()) // zws

// 继承类,继承类属于字类,被继承的属于父类 class Teacher extends Person { getTeacherName() { return ‘zws Teacher’ } // 子类可以重写父类的属性与方法 getName() { // super 关键字指向了父类,可以直接调用父类。不会受到类重写的影响 return super.getName() + ‘TTT’ } }

const teacher = new Teacher() console.log(teacher.getName()) // zws console.log(teacher.getTeacherName()) // zws Teacher

  1. <a name="2RrN6"></a>
  2. ### 类的访问类型和构造器
  3. <a name="oSyrz"></a>
  4. #### 访回类型:
  5. - private:允许在类内使用
  6. - protected:允许在类内及继承的子类中使用
  7. - public:允许在类的内外调用(默认)
  8. <a name="g8Uxt"></a>
  9. #### 自带方法:
  10. - readonly:只读属性
  11. - static:将方法挂载到类上而不是实例上
  12. **tips: **直接写在类里的属性或函数,相当于前面加了public
  13. ```typescript
  14. class Person {
  15. protected name: string = '123'
  16. private age: number = 10
  17. public sayHi() {
  18. console.log('hi' + this.age)
  19. }
  20. }
  21. class Teacher extends Person {
  22. public sayBye() {
  23. return this.name
  24. }
  25. }
  26. const person = new Person()
  27. person.sayHi()
  28. const teacher = new Teacher()
  29. console.log(teacher.sayBye())

构造器 constructor

constructor 会在 new 实例的时候自动执行

  1. // 以下两段代码相同, constructor 里,参数前加上public代表在之前已经声明过这个变量了
  2. // 传统写法
  3. class Person {
  4. public name: string
  5. constructor(name: string) {
  6. this.name = name
  7. }
  8. }
  9. const person = new Person('zws')
  10. // 简化写法
  11. class Person {
  12. // public name: string
  13. constructor(public name: string) {
  14. // this.name = name
  15. }
  16. }
  17. const person = new Person('zws')
  18. console.log(person.name)

字类集成父类并使用 constructor 的话,必须先调用父类的 constructor ,并按照父类的参数规则进行

  1. // super()代表调用父类的 constructor
  2. // 如果父类没有使用constructor 字类需要调用一个空的super()
  3. class Person {
  4. constructor(public name: string) {}
  5. }
  6. class Teacher extends Person {
  7. constructor(public age: number) {
  8. super('zws')
  9. }
  10. }
  11. const teacher = new Teacher(28)

静态属性,Setter和Getter

Getter:
Setter:

  1. // 可以通过getter访问私有属性,通过setter更改私有属性
  2. // 一般用于对数据的加密
  3. class Person {
  4. constructor(private _name: string) {}
  5. get name() {
  6. return this._name + ' has'
  7. }
  8. set name(name: string) {
  9. const realName = name.split(' ')[0]
  10. this._name = realName
  11. }
  12. }
  13. const person = new Person('zws')
  14. console.log(person.name)
  15. person.name = 'zwsa has'
  16. console.log(person.name)

做个小案例

通过 TS 创建一个 Demo 类,这个类只能被调用一次
思路:

  • 不能在外部以new Demo 的形式创建一个实例(将 constructor 设置为私有属性)
  • 使用 static (将方法挂载到类上而不是实例上)来实现
  • 使用 instance 方法来保存传入的值,并判断

    1. class Demo {
    2. private constructor(public name: string) {}
    3. private static instance: Demo
    4. static getInstance(name: string) {
    5. if (!this.instance) {
    6. this.instance = new Demo(name)
    7. }
    8. return this.instance
    9. }
    10. }
    11. const demo1 = Demo.getInstance('zws')
    12. const demo2 = Demo.getInstance('zwsa')
    13. console.log(demo1.name)
    14. console.log(demo2.name)

    抽象类

  • 只能被继承,不能实例化

  • 抽象类里的抽象方法,不能够写具体实现
    1. abstract class Gemo {
    2. width: number
    3. getType() {
    4. return 'Gemo'
    5. }
    6. abstract getArea(): number
    7. }
    8. class Cricle extends Gemo {
    9. // 字类继承了抽象类,里面的抽象方法必须实现一下
    10. getArea() {
    11. return 123
    12. }
    13. }
    14. class Square {}
    15. class Triangle {}