0
点赞
收藏
分享

微信扫一扫

TypeScript 高级类型-详解

凯约 2022-11-04 阅读 136

4. TypeScript 高级类型

概述

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

  1. class 类

  2. 类型兼容性

  3. 交叉类型

  4. 泛型 和 keyof

  5. 索引签名类型 和 索引查询类型

  6. 映射类型

4.1 class 类

TypeScript 全面支持 ES2015 中引入的 class 关键字,并为其添加了类型注解和其他语法(比如,可见性修饰符等)。

class Person {}

const p = new Person()

实例属性初始化:

class Person {
  age: number
  gender = '男'
  // gender: string = '男'
}

const p = new Person()

p.age
p.gender

构造函数:

class Person {
  age: number
  gender: string

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

const p = new Person(18, '男')
console.log(p.age, p.gender)

实例方法:

class Point {
  x = 1
  y = 2

  scale(n: number) {
    this.x *= n
    this.y *= n
  }
}

const p = new Point()

p.scale(10)

console.log(p.x, p.y)

类继承的两种方式:1 .extends(继承父类) 2 .implements(实现接口)。

说明:JS 中只有 extends,而 implements 是 TS 提供的。

extends(继承父类):

class Animal {
  move() {
    console.log('走两步')
  }
}

class Dog extends Animal {
  name = '二哈'

  bark() {
    console.log('旺旺!')
  }
}

const d = new Dog()
d.move()
d.bark()
console.log(d.name)

类继承的两种方式:1 extends(继承父类) 2 implements(实现接口)

implements(实现接口)

interface Singale {
  sing(): void
  name: string
}

class Person implements Singale {
  name = 'jack'

  sing() {
    console.log('你是我的小呀小苹果')
  }
}

类成员可见性:可以使用 TS 来控制 class 的方法或属性对于 class 外的代码是否可见。

可见性修饰符包括:1 public(公有的) 2 protected(受保护的) 3 private(私有的)

1.public:表示公有的、公开的,公有成员可以被任何地方访问,默认可见性。默认可以不写就是public。

// 父类
class Animal {
  public move() {
    console.log('走两步')
  }
}

const a = new Animal()
a.move()

// 子类
class Dog extends Animal {
  bark() {
    console.log('旺旺!')
  }
}

const d = new Dog()
d.move()

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

// 父类
class Animal {
  // 这个方法是受保护的
  protected move() {
    console.log('走两步')
  }

  run() {
    this.move()
    console.log('跑起来')
  }
}

const a = new Animal()
// a.move()  访问不到

// 子类 子类可以访问私有的
class Dog extends Animal {
  bark() {
    this.move()
    console.log('旺旺!')
  }
}

const d = new Dog()
// d

3. private:表示私有的,只在当前类中可见,对实例对象以及子类也是不可见的。

// 父类
class Animal {
  private __run__() {
    console.log('Animal 内部辅助函数')
  }

  // 受保护的
  protected move() {
    this.__run__()
    console.log('走两步')
  }

  // 公开的
  run() {
    this.__run__()
    this.move()
    console.log('跑起来')
  }
}

const a = new Animal()
// a.

// 子类
class Dog extends Animal {
  bark() {
    // this.
    console.log('旺旺!')
  }
}

const d = new Dog()
// d.

除了可见性修饰符之外,还有一个常见修饰符就是:readonly(只读修饰符)。readonly:表示只读,用来防止在构造函数之外对属性进行赋值

/* class Person {
  // 只读属性
  readonly age: number = 18

  constructor(age: number) {
    this.age = age
  }

  // 错误演示:
  // readonly setAge() {
  //   // this.age = 20
  // }
} */

class Person {
  // 只读属性
  // 注意:只要是 readonly 来修饰的属性,必须手动提供明确的类型
  readonly age: number = 18

  constructor(age: number) {
    this.age = age
  }
}

// --

// interface IPerson {
//   readonly name: string
// }

// let obj: IPerson = {
//   name: 'jack'
// }

let obj: { readonly name: string } = {
  name: 'jack'
}

// 这里 name 显示无法赋值,
obj.name = 'rose'

4.2 类型兼容性

两种类型系统:1 Structural Type System(结构化类型系统) 2 Nominal Type System(标明类型系统)。

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

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

// 演示类型兼容性:

// let arr = ['a', 'b', 'c']

// arr.forEach(item => {})
// arr.forEach((item, index) => {})
// arr.forEach((item, index, array) => {})

// 两个类的兼容性演示:
class Point {
  x: number
  y: number
}
class Point2D {
  x: number
  y: number
}

const p: Point = new Point2D()

注意:在结构化类型系统中,如果两个对象具有相同的形状,则认为它们属于同一类型,这种说法并不准确。 更准确的说法:对于对象类型来说,y 的成员至少与 x 相同,则 x 兼容 y(成员多的可以赋值给少的)。

// 两个类的兼容性演示:

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

const p: Point = new Point2D()

class Point3D {
  x: number
  y: number
  z: number
}

const p1: Point = new Point3D()

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

除了 class 之外,TS 中的其他类型也存在相互兼容的情况,包括:1 接口兼容性 2 函数兼容性等。

  • 接口之间的兼容性,类似于 class。并且,class 和 interface 之间也可以兼容。
interface Point {
  x: number
  y: number
}
interface Point2D {
  x: number
  y: number
}
interface Point3D {
  x: number
  y: number
  z: number
}

let p1: Point
let p2: Point2D
let p3: Point3D

// 正确:
// p1 = p2
// p2 = p1
// p1 = p3

// 错误演示:
// p3 = p1

// 类和接口之间也是兼容的
class Point4D {
  x: number
  y: number
  z: number
}
p2 = new Point4D()

  • 函数之间兼容性比较复杂,需要考虑:1 参数个数 2 参数类型 3 返回值类型。
  1. 参数个数,参数多的兼容参数少的(或者说,参数少的可以赋值给多的)。
// 1 参数个数: 参数少的可以赋值给参数多的
type F1 = (a: number) => void
type F2 = (a: number, b: number) => void

let f1: F1
let f2: F2

f2 = f1

// 错误演示:
// f1 = f2

  • 函数之间兼容性比较复杂,需要考虑:1 参数个数 2 参数类型 3 返回值类型。
  1. 参数类型,相同位置的参数类型要相同(原始类型)或兼容(对象类型)
// 2 参数类型: 相同位置的参数类型要相同或兼容

// 原始类型:
// type F1 = (a: number) => void
// type F2 = (a: number) => void

// let f1: F1
// let f2: F2

// f1 = f2
// f2 = f1

// --

// 对象类型
interface Point2D {
  x: number
  y: number
}
interface Point3D {
  x: number
  y: number
  z: number
}

type F2 = (p: Point2D) => void // 相当于有 2 个参数
type F3 = (p: Point3D) => void // 相当于有 3 个参数

let f2: F2
let f3: F3

f3 = f2

// f2 = f3

  • 函数之间兼容性比较复杂,需要考虑:1 参数个数 2 参数类型 3 返回值类型。
  1. 参数类型,相同位置的参数类型要相同或兼容。
// 3 返回值类型,只需要关注返回值类型本身即可

// 原始类型:
type F5 = () => string
type F6 = () => string

let f5: F5
let f6: F6

f6 = f5
f5 = f6

// 对象类型:
type F7 = () => { name: string }
type F8 = () => { name: string; age: number }

let f7: F7
let f8: F8

f7 = f8

// 错误演示
// f8 = f7

4.3 交叉类型

交叉类型(&):功能类似于接口继承(extends),用于组合多个类型为一个类型(常用于对象类型)。比如,

// interface Point2D {
//   x: number
//   y: number
// }

// // 通过继承 Point3D 具有 x/y/z 三个属性
// interface Point3D extends Point2D {
//   z: number
// }

// let p3: Point3D = {
//   x: 1,
//   y: 2,
//   z: 3
// }

// --

interface Person {
  name: string
  say(): number
}
interface Contact {
  phone: string
}

type PersonDetail = Person & Contact

let obj: PersonDetail = {
  name: 'jack',
  phone: '133....',
  say() {
    return 1
  }
}

type PersonDetail = { name: string; phone: string }

交叉类型(&)和接口继承(extends)的对比:

  • 相同点:都可以实现对象类型的组合。

  • 不同点:两种方式实现类型组合时,对于同名属性之间,处理类型冲突的方式不同。

// 对比:
// 继承
// interface A {
//   fn: (value: number) => string
// }
// 这里 B 会报错
// interface B extends A {
//   fn: (value: string) => string
// }

// -- 交叉类型
interface A {
  fn: (value: number | boolean) => string
}
interface B {
  fn: (value: string) => string
}

type C = A & B

let c: C = {
  fn(value: number | string | boolean) {
    return value + ''
  }
}

console.log(c.fn(true));


// let c: C = {
//   fn(value: string) {}
// }

// let c: C = A.fn(11) => { console.log(11) }

说明:以上代码,接口继承会报错(类型不兼容);交叉类型没有错误,可以简单的理解为

fn: (value: string | number) => string

4.4 泛型

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

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

function id(value: number): number { return value }

比如,id(10) 调用以上函数就会直接返回 10 本身。但是,该函数只接收数值类型,无法用于其他类型。

为了能让函数能够接受任意类型,可以将参数类型修改为 any。但是,这样就失去了 TS 的类型保护,类型不安全。

function id(value: any): any { return value }   // 不安全

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

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

创建泛型函数:

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

调用泛型函数:

// 使用泛型来创建一个函数:

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

// 调用泛型函数:

// 1 以 number 类型调用泛型函数
const num = id<number>(10)

// 2 以 string 类型调用泛型函数
const str = id<string>('a')
const ret = id<boolean>(false)

简化调用泛型函数:

// 使用泛型来创建一个函数:
function id<Type>(value: Type): Type {
  return value
}

// 调用泛型函数:

// 1 以 number 类型调用泛型函数
const num = id<number>(10)

// 2 以 string 类型调用泛型函数
const str = id<string>('a')

// --

let num1 = id(100)
let str1 = id('abc')

泛型约束:

泛型约束:默认情况下,泛型函数的类型变量 Type 可以代表多个类型,这导致无法访问任何属性。比如,id(‘a’) 调用函数时获取参数的长度:

在这里插入图片描述

添加泛型约束收缩类型,主要有以下两种方式:1 指定更加具体的类型 2 添加约束

  1. 指定更加具体的类型
function id<Type>(value: Type[]): Type[] {
  value.length
  return value
}

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

  1. 添加约束
interface ILength {
  length: number
}

function id<Type extends ILength>(value: Type): Type {
  value.length
  return value
}

id(['a', 'c'])
id('abc')
id({ length: 10, name: 'jack' })

// 错误演示
// id(123)

泛型的类型变量可以有多个,并且类型变量之间还可以约束(比如,第二个类型变量受第一个类型变量约束)。

比如,创建一个函数来获取对象中属性的值:

function getProp<Type, Key extends keyof Type>(obj: Type, key: Key) {
  return obj[key]
}

getProp({ name: 'jack', age: 18 }, 'age')
getProp({ name: 'jack', age: 18 }, 'name')

// 补充:(了解)
getProp(18, 'toFixed')
getProp('abc', 'split')
getProp('abc', 1) // 此处 1 表示索引
getProp(['a'], 'length')
getProp(['a'], 1000)

console.log('object'[1]) // b

// 错误演示:
// getProp({ name: 'jack', age: 18 }, 'name1')

泛型接口:

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

interface IdFunc<Type> {
  id: (value: Type) => Type
  ids: () => Type[]
}

let obj: IdFunc<number> = {
  id(value) {
    return value
  },
  ids() {
    return [1, 3, 5]
  }
}

实际上,JS 中的数组在 TS 中就是一个泛型接口。
在这里插入图片描述

泛型类:class 也可以配合泛型来使用。

比如,React 的 class 组件的基类 Component 就是泛型类,不同的组件有不同的 props 和 state。

// class GenericNumber<NumType> {
//   defaultValue: NumType
//   add: (x: NumType, y: NumType) => NumType

//   constructor(value: NumType) {
//     this.defaultValue = value
//   }
// }
// 此时,可以省略 <类型> 不写。因为 TS 可以根据传入的参数自动推导出类型
// const myNum = new GenericNumber(100)
// myNum.defaultValue = 10

// --

class GenericNumber<NumType> {
  defaultValue: NumType
  add: (x: NumType, y: NumType) => NumType
}

// 这种情况下,推荐明确指定 <类型>。因为 TS 无法推导出类型
const myNum = new GenericNumber()
myNum.defaultValue = 10

类似于泛型接口,在创建 class 实例时,在类名后面通过 <类型> 来指定明确的类型。

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

说明:它们都是基于泛型实现的(泛型适用于多种类型,更加通用),并且是内置的,可以直接在代码中使用。

这些工具类型有很多,主要学习以下几个:

  1. Partial

  2. Readonly

  3. Pick<Type, Keys>

  4. Record<Keys, Type>

泛型工具类型 - Partial 用来构造(创建)一个类型,将 Type 的所有属性设置为可选。

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

type PartialProps = Partial<Props>

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

泛型工具类型 - Readonly 用来构造一个类型,将 Type 的所有属性都设置为 readonly(只读)。

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

type ReadonlyProps = Readonly<Props>

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

// 这里赋值就报错 只读
p1.id = '2'
// 当我们想重新给 id 属性赋值时,就会报错:无法分配到 "id" ,因为它是只读属性。

泛型工具类型 - Pick<Type, Keys> 从 Type 中选择一组属性来构造新类型。

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

type PickProps = Pick<Props, 'id' | 'title'>

泛型工具类型 - Record<Keys,Type> 构造一个对象类型,属性键为 Keys,属性类型为 Type。

type RecordObj = Record<'a' | 'b' | 'c', string[]>

// type RecordObj = {
//   a: string[]
//   b: string[]
//   c: string[]
// }

let obj: RecordObj = {
  a: ['a'],
  b: ['b'],
  c: ['c']
}

4.5 索引签名类型

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

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

interface AnyObject {
  [key: string]: number
}

let obj: AnyObject = {
  a: 1,
  abc: 124,
  abcde: 12345
}

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

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

const arr = [1, 3, 5]
arr.forEach

interface MyArray<Type> {
  [index: number]: Type
}
let arr1: MyArray<number> = [1, 3, 5]
arr1[0]

4.6 映射类型

映射类型:基于旧类型创建新类型(对象类型),减少重复、提升开发效率。

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

type PropKeys = 'x' | 'y' | 'z' | 'a' | 'b'
type Type1 = { x: number; y: number; z: number; a: number; b: number }
// 这样书写没错,但 x/y/z 重复书写了两次。像这种情况,就可以使用映射类型来进行简化。

type Type2 = { [Key in PropKeys]: number }

// 错误演示:
// interface Type3 {
//   [Key in PropKeys]: number
// }

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

type Props = { a: number; b: string; c: boolean }

type Type3 = { [key in keyof Props]: number }

在这里插入图片描述

实际上,前面讲到的泛型工具类型(比如,Partial)都是基于映射类型实现的。比如,Partial 的实现:

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

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

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

type Props = { a: number; b: string; c: boolean }

type TypeA = Props['a']

// 模拟 Partial 类型:
type MyPartial<T> = {
  [P in keyof T]?: T[P]
}

type PartialProps = MyPartial<Props>

索引查询类型的其他使用方式:同时查询多个索引的类型

type Props = { a: number; b: number; c: boolean }

// 其他使用方式:
type TypeA = Props['a' | 'b']

type TypeB = Props[keyof Props]

写在最后

✨个人笔记博客✨

星月前端博客
http://blog.yhxweb.top/

举报

相关推荐

0 条评论