TypeScript语法进阶学习

69 阅读1分钟

联合类型

type Id = string | number

交叉类型

interface IdProtocal {
  id: Id
}

interface AskProtocol {
  ask?: string // 非必需
}

type UserProtocal = IdProtocal & AskProtocol //交叉类型

const user: UserProtocal = {
  id: 1
}

泛型

// 定义一个泛型函数
// function identity<T>(value: T): T {
//   return value
// }

const identity = <T>(value: T) => value

// 使用泛型函数
const numberValue = identity<number>(42) // numberValue 的类型是 number
const stringValue = identity<string>('Hello, TypeScript!') // stringValue 的类型是 string

console.log(numberValue) // 输出: 42
console.log(stringValue) // 输出: Hello, TypeScript!

// 泛型接口示例
interface ApiResponse<T> {
  data: T
  success: boolean
  message: string
}

// 使用泛型接口
const response: ApiResponse<string> = {
  data: 'This is a response',
  success: true,
  message: 'Request successful',
}

console.log(response)

// 泛型类示例
class GenericBox<T> {
  private content: T

  constructor(content: T) {
    this.content = content
  }

  getContent(): T {
    return this.content
  }
}

// 使用泛型类
const stringBox = new GenericBox<string>('A string in the box')
console.log(stringBox.getContent()) // 输出: A string in the box

const numberBox = new GenericBox<number>(123)
console.log(numberBox.getContent()) // 输出: 123
interface IData {
  id: number
  name: string
}
const say = <T = IData>(data: T): T => {
  return data
}
say('hello')
say(123)

extends

继承 约束泛型 条件类型推导

// 约束泛型
interface IData {
  id: number
  name: string
}
const say = <T extends IData>(data: T): T => {
  return data
}

say({ id: 1, name: 'hello', age: 18 }) // 至少要有id和name属性

// 条件类型 条件判断
const gender = 'man'
const isMan = gender === 'man' ? true : false
type IsMan<T> = T extends 'man' ? true : never
type IsMan2 = IsMan<'man'>

Infer

用来推到类型,和extends一起使用

const call = (a: string, b: number) => {
  return new Date()
}
// 获取函数返回值类型
type CallResult<T> = T extends () => infer R ? R : never
type CallResultType = CallResult<typeof call>

// 获取函数参数类型
type CallParams<T> = T extends (...args: infer P) => any ? P : never
type CallParamsType = CallParams<typeof call>