TypeScript 入门|青训营笔记

74 阅读3分钟

这是我参与「第四届青训营」笔记创作活动的的第10天

本堂课重点内容

  • 什么是TypeScript?
  • 高级类型

详细知识点介绍

什么是TypeScript?

TypeScript 发展历史

  • 2012-10:微软发布了 TypeScript 第一个版本(0.8)

  • 2014-10:Angular 发布了基于 TypeScript 的2.0版本

  • 2015-04:微软发布了 Visual Studio Code

  • 2016-05:@types/react 发布,TypeScript 可开发 React

  • 2020-09:Vue 发布了3.0版本,官方支持 TypeScript

  • 2021-11:v4.5版本发布

为什么要使用 TypeScript?

比较
JS动态类型
弱类型语言
TS静态类型
弱类型语言
静态类型
  • 可读性增强:基于语法解析 TSDoc, ide 增强

  • 可维护性增强:在编译阶段暴露大部分错误 => 多人合作的大型项目中,获得更好的稳定性和开发效率

JS 的超集
  • 包含于兼容所有 Js 特性,支持共存

  • 支持渐进式引入与升级

基本语法

基础数据类型

/* 字符串 */
const q: string = 'string';
/* 数字 */
const w: number = 1;
/* 布尔值 */
const e: boolean = true;
/* null */
const r: null = null;
/* undefined */
const t: undefined = undefined;

对象类型

const bytedancer: IBytedancer = {
    jobId: 9303245,
    name: 'Lin',
    sex: 'man',
    age: 28,
    hobby: 'swimming',
}


interface Ibytedancer {
    /* 只读属性:约束属性不可在对象初始化外赋值 */
    readonly jobId: number;
    name: string;
    sex: 'man' | 'woman' | 'other';
    age: number;
    /* 可选属性:定义该属性可以不存在 */
    hobby?: string;
    /* 任意属性:约束所有对象属性都必须是该属性的子类型 */
    [key: string]: any;
}

函数类型

function add(x: number, y: number): number {
    return x + y;
}


const mult: (x: number, y: number) => number = (x, y) => x * y;
interface IMult {
    (x: number, y: number): number;
}
const mult: IMult = (x,y) => x * y;

函数重载

/* 对 getDate 函数进行重载,timestamp 为可缺省函数 */
function getDate(type: 'string', timestamp?: string): string;
function getDate(type: 'date', timestamp?: string): Date;
function getDate(type: 'string' | 'date', timestamp?: string): Date | string {
    const date = new Date(timestamp);
    return type === 'string' ? date.toLocaleString() : date;
}


const x = getDate('date'); // X: Date
const y = getDate('string','2018-01-10'); //y: string

数组类型

Typescript 补充类型

Typescript 泛型

function getRepeatArr(target) {
    return new Array(100).fill(target);
}


type IGetRepeatArr = (target: any) => any[];

/* 不预先指定具体的类型,而在使用的时候再指定类型的一种特性 */
type IGetRepeatArrR = <T>(target: T) => T[];

类型别名 & 类型断言

字符串/数字 字面量

高级类型

  • 联合/交叉类型

    • 联合类型:IA | IB:联合类型表示一个值可以是几种类型之一

    • 交叉类型:IA & IB:多种类型叠加到一起成为一种类型,它包含了所需要的所有类型的特性

  • 类型保护与类型守卫

  • 函数返回值类型

    • 关键字【extends】跟随泛型出现时,表示类型推断,其表达可类比三元表达式

    • 关键字【infer】出现在类型推荐中,表示定义类型变量,可以用于指代类型

工程应用

  • web

  • Node

课后个人总结

我个人认为 TypeScript是适合初学者的,初学者也很有必要学习,我个人认为 TS 和 JS 并没有太大的区别,只是有了更多的限制,可以在编写代码时就规避掉很多问题。

引用参考

第四届字节跳动青训营「TypeScript 入门」课程