一文详解TS高级类型

1,113 阅读12分钟

TS 高级类型

概述

TS中高级类型有很多,重点学习以下高级类型

  1. class 类
  2. 类型兼容类
  3. 交叉类型
  4. 泛型 和 keyof
  5. 索引签名类型 和 索引查询类型
  6. 映射类型

1. class类

构造函数

class Person{
    age:number
    gender:string
    constructor(age:number,gender:string){
        this.age = age
        this.gender = gender
    }
}

实例方法

class Point{
    x = 1
    y = 2
    scale(n:number):void{
        this.x = this.x*n
        this.y = this.y*n
    }
}

const p = new Point()
p.scale(10)
console.log(p.x,p.y) //10 20

继承

类继承有两种方式:

  1. extend (继承父类)
  2. implement (实现接口) 说明:js中只有extends,而implement是TS提供的

extend

class Animal{
    move(){
        console.log("Moving along")
    }
}
class Dog extends Animal{
    bark(){
        console.log("汪!")
    }
}
const dog = new Dog()
dog.move()   //Moving along
dog.bark()   //汪! 

implement

interface Singable{
    sing():void
}
class Person implements Singable {
    name:string
    constructor(name:string){
        this.name = name
    }
    sing(){
        console.log("快使用双截棍,哼哼哈嘿!")
    }
}
const Jay = new Person("Jay")
console.log(Jay.name) //Jay
Jay.sing()            //快使用双截棍,哼哼哈嘿!

可见修饰符

  1. public (公有的)
  2. protected(受保护的)
  3. private (私有的)

public

表示共有的、公开的,共有成员可以被任何地方访问,默认可见性,可以直接省略

protected

表示受保护的,仅对其声明所在类和子类中可见(非实例对象)!!!

class Animal{
    protected run(){
        console.log("没事跑两步")
    }
    move(){
        this.run()
        console.log("Moving along")
    }
}
class Dog extends Animal{
    bark(){
        this.run()
        console.log("汪!")
    }
}
const dog = new Dog()
dog.move()  
dog.bark()
// dog.run() 会报错 error TS2445: Property 'run' is protected and only accessible within class 'Animal' and its subclasses.


// 没事跑两步
// Moving along
// 没事跑两步
// 汪!

private

表示私有的,只在当前类中可见,对实例对象子类都是不可见

只读修饰符

readonly

表示只读,用来防止在构造函数之外对属性进行赋值

class Person{
    readonly age:number = 18
    constructor(age:number){
        this.age = age
    }
}
  1. readonly关键字只能修饰属性不能修饰方法
  2. 注意:属性age后面的类型注解(比如,此处的number),如果不加,则age的类型为18(字面量类型)
  3. 接口或者{}表示对象类型,也可以使用readonly

2. 类型兼容性

类型系统一共有两种:

1. Structural Type System (结构化类型系统)
2. Nominal Type System (标明类型系统)

TS使用的是结构化类型系统,也叫作duck typing (鸭子类型),类型检查关注的是值所具有的形状

对象兼容性

也就是说,在结构类型系统中,如果两个对象具有相同的形状,则认为它们属于同一类型。

class Point {x:number;y:number}
class Point2D {x:number;y:number}

let p:Point = new Point2D()

在 Nominal Type System 中,如C#、JAVA,它们是不同的类,类型无法兼容

更准确的说,对于对象类型来说,y的成员至少与x相同,则x兼容y (成员多的可以赋值给少的)

class Point(x:number;y:number)
class Point3D(x:number;y:number,z:number)
let p1:Point = new Point3D()

//错误演示
//let p2:Point3D = new Point()

接口间的兼容性,类似于class

interface Point{x:number;y:number}
interface Point2D{x:number;y:number}

let p1:Point
let p2:Point2D = p1

interface Point3D{x:number;y:number;z:number}
let p3 :Point3D
p2 = p3

class 与 interface 之间也可以兼容

class Point3D {x:number;y:number;z:number}
let p3:Point2D = new Point3D()

函数兼容性

函数之间兼容性比较复杂,需要考虑:

1.参数个数
2.参数类型 
3.返回值类型

1.参数个数

参数多的兼容参数少的,或者说参数少的可以赋值给多的(和对象相反)

type F1 = (a:number)=>void
type F2 = (a:number,b:number)=>void
let f1:F1
let f2:F2 = f1

在JS中省略用不到的函数参数实际上是很常见的,这样的使用方式,促成了TS中函数类型之间的兼容性

2.参数类型

相同位置的参数类型要相同(原始类型)或兼容(对象类型)

3.返回值类型

  1. 如果返回值是原始类型,此时两个类型要相同。
  2. 如果返回值是对象类型,此时参数多的可以赋值给参数少的
type F1 = ()=> {name:string}
type F2 = ()=> {name:string,age:number}
let f7:F7
let f8:F8
f7 = f8 //多的赋值给少的

3. 交叉类型 &

功能类似于接口继承,用于组合多个类型为一个类型

interface Person {name:string}
interface Contact {phone:string}
type PersonDetail = Person & Contact
let obj:PersonDetail = {
    name:'jack',
    phone:"123456789"
}

交叉类型 & 和接口类型 extends 的对比:

  1. 相同点:都可以实现对象类型的组合
  2. 不用点:两种方式实现类型组合时,对于同名属性之间,处理类型冲突的方式不同

接口继承会报错(类型不兼容);交叉类型没有错误,进行|操作。

4. 泛型(重点!!!)

泛型是可以在保证类型安全前提下,让函数等与多种类型一起工作,从而实现复用,常用于:函数接口class中。

泛型保证类型安全(不丢失类型信息)的同时,可以让函数等与多种不同的类型一起工作,灵活可复用

实际上,在 C# 和 JAVA 等编程语言中,泛型都是用来实现可复用组件功能的主要工具之一

需求:创建一个id函数,传入什么数据就返回该数据本身(也就是参数与返回值类型相同)

创建泛型函数:

function id<Type>(value:Type):Type{return value}

解释

  1. 语法:在函数名称得后面添加<>(尖括号),尖括号中添加类型变量,比如此处的Type。
  2. 类型变量Type,是一种特殊类型的变量,它处理类型而不是值
  3. 该类型变量相当于一个类型容器,能够捕获用户提供的类型(具体是什么类型由用户调用该函数时指定)。
  4. 因为Type是类型,因此可以将其作为函数参数和返回值的类型,表示参数和返回值具有相同的类型。
  5. 类型变量Type,可以是任意合法的变量名称。

调用泛型函数

function id<Type>(value:Type):Type{return value}
const num = id<number>(10)
const str = id<string>('a')

解释

  1. 语法:在函数名称得后面添加<>尖括号中指定具体的类型。比如,此处的`number。
  2. 当传入类型number后,这个类型就会被函数声明时指定的类型变量Type捕获到
  3. 此时,Type的类型就是number,所以,函数id参数和返回值的类型都是number

这样,通过泛型就做到了让id函数与多种不同的类型一起工作,实现了复用的同时保证了类型安全

简化调用泛型函数

function id<Type>(value:Type):Type{return value}
let num = id(10)

泛型约束

默认情况下,泛型函数的类型变量Type可以代表多个类型,这导致无法访问任何属性。

function id<Type>(value:Type):Type{
    console.log(value.length)
    return value
}

解释:

Type可以代表任意类型,无法保证一定存在length属性,比如number类型就没有length

此时就需要为泛型添加约束收缩类型(缩窄类型取值范围)

主要有两种方式:

  1. 指定更加具体的类型

     function id<Type>(value:Type[]):Type[]{
         console.log(value.length)
         return value
     }
    

    比如,将类型修改为Type,因为只要是数组就一定存在length属性,因此就可以访问了。

  2. 添加约束

     interface ILength {
         length:number
     }
     function id<Type extends ILength>(value:Type):Type{
         console.log(value,length)
         return value
     }
     const a = id([123])
     const b = id(123)
    

    解释:

    1. 创建描述约束的接口Ilength,该接口要求提供length属性
    2. 通过extends关键字使用接口,为泛型(类型变量)添加约束。
    3. 该约束表示:传入的类型必须具有length属性

泛型的类型变量可以有多个,并且类型变量之间还可以约束

function getProp<Type,key extends keyof Type>(obj:Type,key:Key){
    return obj[key]
}
let person = {name:'wow',age:18}
getProp(person,"name")

解释:

  1. 添加了第二个类型变量Key,两个类型变量之间使用,分隔。
  2. keyof 关键字 接收一个对象类型,生成其键名称(可能是字符串或者数字)的联合类型
  3. 本实例中keyof Type 实际上获取的是person对象所有键的联合类型,也就是'name|age'
  4. 类型变量key受到Type约束,可以理解为:Key只能是Type所有键中的任意一个,或者说只能访问对象中存在的属性。

泛型接口

接口也可以配合泛型来使用,以增加其灵活性,增强其复用性。

interface IdFunc<Type>{
    id:(value:Type)=>Type
    ids:()=>Type[]
}
let obj:IdFunc<number>={
    id(value){
        return value
    }
    ids(){
        return [1,3,5]
    }
}
  1. 在接口名称得后面添加<类型变量>,这个接口就变成了泛型接口
  2. 接口的类型变量,对接口中所有其他成员可见,也就是接口中所有成员都可以使用类型变量
  3. 使用泛型接口时,需要显示指定具体的类型(比如:此处的IdFunc<number>)
  4. 此时,id方法的参数和返回值类型都是number,ids方法返回值的类型是number[]

泛型类

class 也可以配合泛型来使用 比如:React的class组件的基类Component就是泛型类,不同的组件有不同的props和state

interface IState {count:number}
interface Iprops {maxLength:number}
class InputCount extends React.Component<Iprops,Istate>{
    state:IState = {
        count:0
    }
    render(){
        return <div>{this.props.maxLength}</div>  
    }
}

构造泛型类

class GenericNumber<NumType>{
    defaultValue:NumType
    add!: (x: NumType, y: NumType) => NumType
    constructor(value:NumType){
        this.defaultValue = value
    }
}

const myNum = new GenericNumber<number>(10)
// myNum.defaultValue = 10

console.log(myNum)

泛型工具类型

TS内置了一些常用的工具类型,来简化TS中的一些简常见操作。

说明:它们都是基于泛型实现的,并且是内置的,可以直接在代码中使用。这些工作类型有很多,主要学习以下几种

1. Partial<Type>

用来构建一个类型,将Type的所有属性设置为可选

interface Props{
    id:string
    children:number[]
}
type PartialProps = Partial<Props>

解释:构造出来的新类型 PartialProps 结构和 Props 相同,但所有属性都变为可选的

interface Props{
    id:string
    children:number[]
}


type PartialProps = Partial<Props>

let p1:Props = {
    id:"",
    children:[1,2,3]
}
let p2:PartialProps = {}


//手写Partial
type myPartial<T> = {
    //遍历所有的属性,把 :  --> ?:
    //就是必选:  变为 可选 ?
    [P in keyof T]?:T[P];
};
type myPartialProps = myPartial<Props>
let p3:myPartialProps = {}

console.log(p1,p2,p3)  //{ id: '', children: [ 1, 2, 3 ] } {} {}

2. Readonly<Type>

构建一个类型,将Type的所有属性都设置为 readonly(只读)

interface Props{
    id:string
    children:number[]
}

type ReadonlyProps = Readonly<Props>

let props:ReadonlyProps = {id:'1',children:[]}

props.id = '2'   //标红报错

//手写 Readonly
type myReadonly<T>={
    readonly [p in keyof T]: T[p]
}
type myReadonlyProps = myReadonly<Props>
let props2:myReadonlyProps = {id:'2',children:[1,2,3]}
props2.id = '1'  //标红报错

3. Pick<Type,Keys>

从Type中选择一组属性来构造新类型

interface Props{
    id:string
    title:string
    children:number[]
}
type PickProps = Pick<Props,'id'|'title'>

解释

1. Pick 工具类型有两个类型变量:1.表示选择谁的属性 2. 表示选择哪几个属性
2. 其中第二个类型变量,如果只选择一个则只传入该属性名即可。
3. `第二个类型变量传入的属性只能是第一个类型变量中存在的属性。`
4. 构造出来的新类型PickProps,只有id和title两个属性类型。
interface Props{
    id:string
    title:string
    children:number[]
}
type PickProps=Pick<Props,'id'|'title'>

let props:PickProps={
    id:"1",
    title:"标题"
}

console.log(props.id)

//手写 Pick,我字节一面的原题,没写出来....

interface Todo { 
    title: string; 
    description: string; 
    completed: boolean; 
}
type myPick<T,K extends keyof T> = {
    [P in K]:T[P]
}
type TodoPreview = myPick<Todo, 'title' | 'completed' >;

const todo: TodoPreview = { 
    title: 'Clean room' , 
    completed: false, 
};

4. Record<Keys,Type>

构造一个对象类型,属性键为Keys,属性类型为Type

type RecordObj = Record<'a'|'b'|'c',string[]>
let obj:RecordObj={
    a:['1'],
    b:['2'],
    c:['3']
}

console.log(obj)
//{ a: [ '1' ], b: [ '2' ], c: [ '3' ] }

// 手写Record
type myRecord<K extends string|number|symbol,T> = {
    [P in K]:T
}
type myRecordObj = myRecord<'q'|'w'|'e',string[]>
let obj2:myRecordObj={
    q:['1'],
    w:['2'],
    e:['3']
}
console.log(obj2)
//{ q: [ '1' ], w: [ '2' ], e: [ '3' ] }

解释:

1. Record工具类型有两个类型变量:1. 表示对象有哪些属性 2. 表示对象属性的类型
2. 构建的新对象类型 RecordObj 表示:这个对象有三个属性分别为 a/b/c,属性值类型都是string[]

5. 索引签名类型

绝大多数情况下,我们都可以在使用对象前就确定对象的结构,并为对象添加准确的类型

使用场景:当无法确定对象中有哪些属性,或者说对象中可以出现任意多个属性,此时就用到索引签名类型了。

interface AnyObject{
    [key:string]:number
}
let obj:AnyObject = {
    a:1,
    b:2
}

解释:

1. 使用`[key:string]`来约束该接口中允许出现的属性名称。表示只要是string类型的属性名称,都可以出现在对象中。
2. 这样,对象obj中就可以出现任意多个属性(比如:a,b等)。
3. `key知识一个占位符`,可以换成任意合法的变量名称。
4. 隐藏的前置知识:`js中对象({})的键是string类型的`

在JS中数组是一类特殊的对象,特殊在数组的键(索引)是数值类型

并且,数组中也可以出现任意多个元素,所以,在数组的泛型接口中,也用到了索引签名类型。

interface MyArray<T>{
    [index:number]:T
}
let arr:MyArray<number> = [1,3,5]

解释

  1. MyArray接口模拟原生的数组接口,并使用[index:number]来作为索引签名类型
  2. 该索引签名类型表示:只要是number类型的键(索引)都可以出现在数组中,或者说数组中可以有任意多个元素。
  3. 同时也符合数组索引是number类型这一前提。

6. 映射类型

基于就类型创建新类型(对象类型),减少重复、提升开发效率

比如,类型 PropKeys 有x/y/z,另一个类型Type1中也有x/y/z,并且Type1中的x/y/z的类型相同

//联合类型
type PropKeys = 'x'|'y'|'z'
type Type1 = {x:number;y:number;z:number} 

这种情况,就可以使用映射类型来简化

type PropKeys = 'x'|'y'|'z'
type Type2 = {[Key in PropKeys]:number}

解释

  1. 映射类型是基于索引签名类型的,所以,该语法类似于索引签名类型,也使用了[]
  2. Key in PropKeys 表示 Key 可以是PropKeys联合类型中的任意一个类似于for(let key in PropKeys)
  3. 使用映射类型创建的新对象类型Type2和类型Type1结构完全相同。
  4. 注意:映射类型只能在类型别名中使用,不能在接口中使用

映射类型除了根据 联合类型 创建新类型外,还可以根据 对象类型 来创建

type Props = {a:number;b:string;c:boolean}
type Typesc = {[key in keyof Props]:number}

解释

  1. 首先执行keyof Props 获取到对象类型Props中所有键的联合类型即,'a'|'b'|'c'
  2. 然后,Key in ... 就表示Key 可以是Props中所有的键名称中的任意一个

分析泛型工具类型Partial的实现

type Partial<T>={
    [P in keyof T]?:T[P]
}

type Props = {a:number;b:string;c:boolean}
type PartialProps = Partial<Props>

解释:

1. `Keyof T` 即keyof Props 表示获取Props的所有键,也就是:'a'|'b'|'c'
2. 在[]后面添加`?`(问号),表示将这些属性变成`可选`的,以此来实现Partial的功能。
3. 冒号后面的`T[P]表示获取T中每个键对应的类型`。比如,如果是'a'则类型是number;如果是'b'则类型是string4. 最终,新类型PartialProps和就类型Props结构完全相同,知识所有值变成可选的了

索引查询类型

刚刚用到的T[P]语法,在TS中叫做索引查询(访问)类型

作用:用来查询属性的类型

type Props = {a:number;b:string;c:boolean}
type TypeA = Props['a']   //number

[]中的类型必须存在于被查询类型中,否则就会报错。

也可以同时查询多个类型

type Props = {a:number;b:string;c:boolean}
type TypeA = Props['a'|'b']   // string | number
type TypeB = props[keyof Props]//string | number | boolean