Allen Yu Allen Yu
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
Home
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《TypeScript入门教程》
GitHub (opens new window)
  • 开始

  • 基础

    • 原始数据类型
    • 任意值
    • 类型推论
    • 联合类型
    • interfaces
    • 数组类型
    • 函数类型
    • 类型断言
    • 声明文件
    • 内置对象
    • keyof and typeof
      • keyof
      • typeof
      • 参考
    • extends
  • 进阶

  • 实战

  • TypeScript
  • 基础
2022-03-25
目录

keyof and typeof

# keyof

它用来遍历和提取类型系统中的 key 值,并返回一个用字面量类型组合成的新类型。

举个 🌰

interface Person {
  name: string
  age: number
  sex: string
}

// 获取 Person 类型中的 key 的联合字面量类型
type PersonProperty = keyof Person

// 等价于
type PersonProperty = 'name' | 'age' | 'sex'

type PersonUnion = Person[keyof Person]

// 等价于
type PersonUnion = string | number

# typeof

当我们有一个对象实例,但是没有这个对象的 interface 时,可以通过 typeof 定义一个。

举个 🌰

const Me = {
  name: 'Allen',
  age: 18,
  sex: 'male',
}

type Person = typeof Me

// 等价于
interface Person {
  name: string
  age: number
  sex: string
}

如果是一个数组呢?

const cat = ['kitty', 2, 12, true]

type Cat = typeof cat

// 等价于
type Cat = (string | number | boolean)[]

# 参考

  • Keyof Type Operator (opens new window)
  • Typeof Type Operator (opens new window)
  • 简单易懂的 keyof typeof 分析 (opens new window)
Last Updated: 3/30/2022, 1:20:25 AM
内置对象
extends

← 内置对象 extends→

最近更新
01
4 月第 2 周总结
04-17
02
工具类型
04-01
03
Google 搜索小技巧
03-28
更多文章>
Theme by Vdoing | Copyright © 2018-2022 Allen Yu
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式