# 关键字

# typeof

  • typeof会将变量变成 typescript 的接口
const person = {
  name: 'tom',
  age: 18
}
type person = typeof person

# keyof

  • 返回当前变量的所有key
  • keyof 接口或者变量的结果 一般可以和 in 搭配使用
interface Person {
  name: string
  age: number
  sex: string
}

type K1 = keyof Person // 'name' | 'age' | 'sex'

// 搭配 typeof
const obj = {
  id: 1,
  name: 'zq'
}
const key: keyof typeof obj  = 'id' // 'id' | 'name'

# in

interface A {
  name: string
  age: number
}

interface B {
  name: string
  sex: string
}

function exep(data: A | B) {
  // 如果使用 普通的 data.age 会报错 因为 Person 有可能是 B接口 多以使用 in
  if ('sex' in data) {
    return data.sex
  } else {
    return data.age
  }
}

# is

  • 当一个函数需要通过变量或者属性的处理返回 true 或 着false 时 需要使用is进行类型推断
function isString(str: unkonw): str is string {
  return typeof str === 'string'
}

// 当 isString 返回 true 代表 str 是 string 类型
if (isString(ss)) {
  ss.charAt(0)
}