Skip to content

Typescript 使用实例 #4

Description

@wangkailang

keyof 索引

  • 类的保护或私有属性不能被 keyof 获取到
class ClassExample {
  private name: string;
  public readonly age: number;
  protected home: string;
}

type ClassType = keyof ClassExample
// => age

T[k] 索引访问

  • T[keyof T] 可以访问到 T 中所有类型组成的联合类型
interface Alice {
  name: string,
  readonly age: number,
}

type AliceType1  = Alice['name' | 'age']
// => string | number
type AliceType2 = Alice[keyof Alice]
// => string | number

交叉类型

  • 交叉类型并集,有相同 key 但是类型不同,该 key 为 never 类型
interface Alice {
  name: string,
  age: number,
}

interface Blob {
  color: string,
  age: string,
}

type T = Alice & Blob

type UnionAge = T['age']
// => never

extends 关键词

条件类型,可用于条件判断

Distributive Conditional Types

interface Animal {
  name: string;
}

interface Dog extends Animal {
  break(): void;
}

let animal1: Animal = { name: 'animal1' };
let dog1: Dog = { name: 'dog1', break: () => {} };

// ✅ 子类型更佳具体,可以赋值给更佳宽泛的父类型
animal1 = dog1

// ❌ Property 'break' is missing in type 'Animal' but required in type 'Dog'
dog1 = animal1

let animalArr: Array<Animal> = [{ name: 'animal1' }]
let dogArr: Array<Dog> = [{ name: 'dog1', break: () => {} }];
// ✅ 协变 子 => 父
animalArr = dogArr

type AnimalFn = (arg: Animal) => void
type DogFn = (arg: Dog) => void

let animalFn: AnimalFn = a => {};
let dogFn: DogFn = a => {};

// 逆变 type Fn<T> = (arg: T) => void 构造器构造后,父子关系逆转了
// ❌  Type 'Animal' is not assignable to type 'Dog'
animalFn = dogFn
// ✅
dogFn = animalFn

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions