TypeScript 入门 | 青训营笔记

50 阅读1分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 4 天

1、为什么什么是 TypeScript?

静态类型

  • 可读性增强:基于语法解析 TSDoc,ide 增强
  • 可维护性增强:在编译阶段暴露大部分错误

多人合作的大型项目中,获得更好的稳定性和开发效率

JS 的超集:

  • 包含于兼容所有 Js 特性,支持共存
  • 支持渐进式引入与升级

2、TypeScript 基本语法

2.1、基本类型

  • 布尔值
  • 数字
  • 字符串
  • 数组
  • 元组
  • 枚举
  • Any
  • Void
  • Null 和 Undefined
  • Never
  • Object
基础数据类型
const q:'string';
对象类型
const bytedancer:IBytedancer={
    id:123,
    name:'zhangsan'
}

interface IBytedancer{
    readonly id:number,
    name:string
}
函数类型
function add(x:number,y:number):number{
    return x+y
}
数组类型
type arr1=number[];

type arr2=Array<string|number>

2.2、接口

  • 可选属性
  • 只读属性
interface IBytedancer{
    readonly id:number,
    name:string
}

2.3、函数

  • 函数声明
  • 函数表达式
  • 箭头函数
  • 函数重载
function add(x:number,y:number):number{
    return x+y
}

2.4、泛型

  • 泛型函数
  • 泛型类
  • 泛型约束
interface iMac<T,U>{
    key:T,
    value:U
}

2.5、类型别名&类型断言

type Arr=Array<{
key:string;
[objKey:string]:any;
}>

3、高级类型

// 联合类型
let unionType: string | number;
unionType = 1;

// 类型保护
function getLength(input: string | number): number {
  const str = input as string;
  if (str.length) {
    return str.length;
  } else {
    const number = input as number;
    return number.toString().length;
  }
}

// 类型守卫

function getLength(input: string | number): number {
  if (typeof input === 'string') {
    return input.length;
  } else {
    return input.toString().length;
  }
}

//函数返回值类型

function getLength(input: string | number): number {
  if (typeof input === 'string') {
    return input.length;
  } else {
    return input.toString().length;
  }
}