Day05 深入简出TypeScript | 青训营

112 阅读5分钟

Day05 深入简出TypeScript

什么是typescript

  • 一个JavaScript超集
  • TypeScripe扩展 JavaScript,并添加了类型
  • 可以在任何支持JavaScript的平台中执行
  • 以JavaScript为基础构建的语言
  • TS不能被JS解析器直接执行

image-20230802104158178

基础

TS基础类型

  • boolean 、 number 、 string
  • undefined 、 null
  • any 、 unknown 、 void4 , never
  • 数组类型[]
  • 元组类型 tuple

TS函数类型

定义. TS 定义函数类型时要定义输入参数类型和输出类型

  • 输入参数:参数支持可选参数和默认参数
  • 输出参数:输出可以自动推断,没有返回值时,默认为 void 类型
  • 函数重载、名称相同但参数不同,可以通过重载支持多种类型
function add(x: number[]): number
function add(x: string[]): string
function add(x: any[]): any {
    if (typeof x[0]=== 'string ' ) {
        return x.join()
        }
    if (typeof x[0]=== 'number' ) {
        return x.reduce((acc,cur) =>acc + cur)
        }
    }

TS接口-interface

定义︰接口是为了定义对象类型

特点:

  • 可选属性:?
  • 只读属性:readonly
  • 可以描述函数类型
  • 可以描述自定义属性

总结:接口非常灵活duck typing

interface Person i
name: stringage: number
}
const pl : Person = {
name: 'lin',
age: 18
}

TS类

定义:写法和 JS 差不多,增加了一些定义

特点:

  • 增加了 public 、 private 、 p rotected 修饰符

  • 抽象类:

    • 只能被继承,不能被实例化
    • 作为基类,抽象方法必须被子类实现
  • interface 约束类,使用 implements 关键字

abstract class Person{
    projected name:string
    private age:number
    public constructor(name:string){
        this.name=name
    }
    public abstract sayHi():void
}
class Student extends Person{
    constructor(name:string){
        super(name)
    }
    sayHi():void{
        console.log('你好!')
    }
}

进阶

联合类型 |

let num=number|string
num=8
num='eight'

交叉类型 &

TS交叉类型(Intersection Types)是一种用于组合多个类型的类型操作符。它允许你将多个类型合并成一个类型,新类型将包含所有原始类型的属性和方法。

interface Person {
  name: string;
  age: number;
}
​
type student:Person&{grade:number}
const stu:student
console.log(stu)        //{name:string,age:number,grade:number}

类型断言

在 TypeScript 中,类型断言是一种告诉编译器某个值应该被视为特定类型的方式。它可以在需要明确指定类型的地方使用,以便在编译时通过类型检查。类型断言有两种形式:尖括号语法和as语法。

let str: any = "hello";
let len1: number = (<string>str).length;
let str: any = "hello";
let len2: number = (str as string).length;

使用场景

  • 消除类型检查错误 有些情况下,开发者明确知道某个变量的类型,但是TypeScript的类型检查器并不能推断出这个类型。这时可以使用类型断言,将变量的类型强制转换为开发者指定的类型,从而消除类型检查错误。
  • 处理联合类型 当一个变量的类型是多种类型的联合类型时,如果开发者想要使用其中一个类型的属性或方法,可以使用类型断言将其转换为该类型,以便进行后续操作。
  • 处理any类型 有时开发者需要使用any类型的变量,但是any类型会降低代码的类型安全性。如果能够明确知道该变量的类型,可以使用类型断言将其转换为该类型,以提高代码的类型安全性。

类型别名 type alias

typescript 中, 我们声明类型有两种方式: 接口(interface) 和类型别名(type alias)

类型别名(type aliases)为一个类型创建一个新的名字。有些时候类型别名与接口(interfaces)很相似,但是类型别名可以用于声明原始类型(primitives),联合类型(unions),元组类型(tuples),还有其它一些你必须要手写的类型。

区别

声明对象和函数类型的语法不一样

interface

interface A {
  x: number;
  y: string;
}
interface B {
  (x: number, y: string): void;
}

type alias

type A = {
  x: number;
  y: number;
};
type B = (x: number, y: string) => void;
类型别名(type alias)可以用来声明一些接口(interface)无法声明的其他类型
// 声明已有类型(即取别名)
type A = number;
// 字面量类型
type B = 'foo';
// 元组类型
type C = [number, string];
// 联合类型
type D = number | boolean;
// 交叉类型
type E = A & D;
接口(interface)通过 extends 关键字来扩展一个类型(这个类型可以是 interface, 也可以是 type alias),类型别名(type alias)则通过交叉类型来实现扩展

interface

interface Super {
  a: string;
}
interface Sub extends Super {
  b: number;
}

type alias

type Super = {
  a: string;
};
type Sub = Super & { 
  b: number 
};
在类型别名(type alias)的声明中可以使用 keyoftypeofin 等关键字来进行一些强大的类型操作
interface A {
  x: number;
  y: string;
}
// 拿到 A 类型的 key 字面量枚举类型,相当于 type B = 'x' | 'y'
type B = keyof A;

const json = { foo: 1, bar: 'hi' };
// 根据 ts 的类型推论生成一个类型。此时 C 的类型为 { foo: number; bar: string; }
type C = typeof json;

// 根据已有类型生成相关新类型,此处将 A 类型的所有成员变成了可选项,相当于 type D = { x?: number; y?: string; };
type D = {
  [T in keyof A]?: A[T];
};
接口(interface)可以通过合并不同的声明进行不断扩展
interface A {
  x: number;
}
interface A {
  y: number;
}
// 经过上面两次声明后 A 的类型为: { x: number; y: number; }

泛型

基本定义

  • 泛型的语法是<>里面写类型参数,一般用T表示;

  • 使用时有两种方法指定类型:

    • 定义要使用的类型
    • 通过TS类型推断,自动推导类型
  • 泛型的作用是临时占位,之后通过传来的类型进行推导

基础操作符

  • typeof:获取类型
  • keyof:获取所有键
  • in:遍历枚举类型
  • T[K]:索引访问
  • extends:泛型约束

常用工具类型

  • Partial:将类型属性变为可选
  • Required:将类型属性变为必选
  • Readonly:将类型属性变为只读
  • Pick、Record...

声明文件

  • declare:三方库需要类型声明文件
  • .d.ts:声明文件定义
  • types:三方库TS类型包
  • tsconfig.json:定义TS的配置

结语

typescript是JavaScript的超集,现在越来越多的框架或者公司支持typescript,他让js代码更加严谨,定义变量的类型,避免了很多低级错误,泛型的使用也减少了很多重复性劳动,加油一起学好TS!