前端知识点——TypeScript

写在前面

笔记内容大多出自于拉勾教育大前端高薪训练营的教程,因此也许会和其他文章雷同较多,请担待。

兼容 tsconfig.json

  • 将target设置为需要兼容到的版本,然后在lib中以数组方式添加从兼容版本到目前为止的所有版本,还要添加DOM来引用DOM对象

原始数据类型

const a: string = 'aeorus'
const b: number = 100 // NaN Infinity
const c: boolean = true // false
// 在非严格模式(strictNullChecks)下,
// string, number, boolean 都可以为空
// const d: string = null
// const d: number = null
// const d: boolean = null
const e: void = undefined
const f: null = null
const g: undefined = undefined
// Symbol 是 ES2015 标准中定义的成员,
// 使用它的前提是必须确保有对应的 ES2015 标准库引用
// 也就是 tsconfig.json 中的 lib 选项必须包含 ES2015
const h: symbol = Symbol()

Object类型

  • function() {} / {} / [] -> 函数/对象/数组都属于对象类型

数组类型

const arr: Array<number> = [1, 2, 3]
const arr: number[] = [1, 2, 3]

元祖类型

const tuple: [number, string] = [1, "1"]

枚举

/*
在枚举前加上const可以使编译后的代码显示具体的枚举item所对应的值,如果不加则会多出一组双向键值对对象的定义 -> Status[Status["PENDING"] = 'pending'] = "PENDING",如此就可以从Status['PENDING']中获得'pending',也可以从Status['pending']中获得'PENDING'了
const enum Status {
  PENDING = 'pending',
  FULFILLING = 'fulfilling',
  REJECTED = 'rejected',
}
*/
enum Status {
   
  PENDING = 'pending',
  FULFILLING = 'fulfilling',
  REJECTED = 'rejected',
}
console.log(Status.PENDING)

函数类型

function foo(num: number): void {
   
  console.log(num)
}
const foo: (num: number) => void = function (num: number): void {
   
  console.log(num)
}
const foo: (num: number) => void = (num: number): void => {
   
  console.log(num)
}

任意类型

  • any不会做类型检查,所以写起来其实和js无异,js有的弱类型通病在any类型定义的变量里依然存在

断言

const arr = [1, 2, 3]
const res = arr.find(i => i > 2)
// 开发者明确知道这里res肯定是number类型,但是类型推断认为可能存在undefined的可能性,所以使用断言,明确这个值就是number类型
const asNum = res as number // 如此,asNum的类型只会为number类型

接口

interface IPerson {
   
  name: string
  age: number
  gender?: boolean
  readonly hobby: string[]
  [props: string]?: string
}
const me: IPerson = {
   
  name: 'aeorus',
  age: 27,
  hobby: ['female']
}
const you: IPerson = {
   
  name: 'somebody',
  age: 0,
  gender: false,
  hobby: ['male', 'female']
}
// you.hobby = ['male'] -> 会报错

Class

class Person {
   
  name: string = 'aeorus'
  age: number // 这里没有给初始值,则一定要在constructor里面进行赋值,不然会报错
  private gender: boolean // 私有属性,只能在类里面访问到
  protected hobby: string[] // 私有属性,但是继承的子类可以访问到
  // protected readonly hobby: string[] // 私有属性且只读,无论在类的内部或者外部,都无法进行修改
  constructor(name: string, age: number, gender: boolean) {
   
    this.name = name
    this.age = age
    this.gender = gender
  }
  checkGender() {
   
    console
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值