TS新手指南之那些常用的字符

1,140 阅读2分钟

引言

你是否有过在面对高工的TS代码中各种字符不知其所以然? 随着TS的普遍. 日常开发中书写TS也成为了我们不可或缺的一部分. 强大的类型检查.类型推导等等属性让我们编写的代码更加严谨. 之前写过的TS新手指南 帮忙我们了解TS. 今天我们继续由浅入深. 一起了解下TS中的那些常用的特殊字符.

TS中的 :

相信 : 字符大家都不会陌生. 其含义为类型注解


const name:string = '' // 意为当前变量name为字符串类型

TS中的 ?

  1. 可选链 TS 3.7 版本中实现了ECMAScript 的功能: 可选链. 使我们在访问null和undefined阻止表达式的运行

const obj = {}
const a = obj?.name // 不会error

  1. 可选属性

interface IParams{
  name?:string, //表述name属性可有可无
  age: number
}

TS中的 ??

TS 3.7 版本中引入了 ?? 空值合并运算符(当左侧数值为null或者undefined时 返回右侧的数值)


// ?? 和 || 的区别
const name = null ?? 'renlingxin' // 'renlingxin'
const age = null || 'renlingxin' // 'renlingxin'

const name = false ?? 'renlingxin' // false
const age = false || 'renlingxin' // 'renlingxin'

// 函数表达式同样适用
function A(){ return null }
function B(){ return 1 }

const res = A() ?? B()

TS 中的 &

& 可用于合并类型

  // 类型合并
  interface IC { c: string }
  interface IA { a: number }
  type Params = IC & IA // { c: string, a: number }
  
  // 重名合并
  interface IB { b: string }
  interface ID { b: number }
  type Params = IB & ID// { b: never }
  
  // 补充 同时声明两个同名的 interface 会相互合并
  interface IN { a: string }
  interface IN { c: number }
  btn:IN = { a:'', c:22 } //IN 合并
  

TS 中的 |

| 表示联合类型 意为既


type Name = string | undefined // 意为 Name 属性不仅可以是string同时也可以是undefined

TS 中的 <> 和 as 和 !

<> 和 as 和 !多用于类型断言. as 表示该类型可预料的某Type. !则表示该变量不会是 null 和 undefined


const time:any = 'shiguangrengran'
const tiemLength:number = (<String>time).length // <type> 表示time将会是type类型.


const time:any = 'shiguangrengran'
const tiemLength:number = (time as String).length//as 将 time 的类型断言为字符串. 以避免TS的类型检查


class app extends Vue{
   @Props()
   name!:string = 'renlingxin' // ! props name不会是null或undefined即必传属性
}

TS 中的 -

  • 意为移除
  
  // 工具类型 Required 的内部实现 -? 移除可选属性
  type Partial<T> = {
      [P in keyof T]-?: T[P];
  };
  

最后

欢迎大家一起补充~