ts 泛型基础介绍

泛型:指的是,在定义函数/接口/类型...时,不预先指定具体的类型,而是在使用的时候再指定类型限制的一种特性


当我们定义一个变量,但不确定其类型的时候,有两种解决方式:

  1. 方式1:使用any
    使用any定义时存在的问题:虽然已知道传入值的类型,但是无法获取函数返回值的类型;另外也失去了ts类型保护的优势。
  2. 方式2:使用泛型
    泛型:在定义函数/接口/类型...时,不预先指定具体的类型,而是在使用的时候再指定类型限制的一种特性。

  1. 在函数中使用泛型
    使用方式:类似于函数传参,传什么数据类型,T就表示什么数据类型,使用时T也可以换成任意字符串
javascript 复制代码
function test<T>(arg: T): T {
  console.log('泛型=', arg)
  return arg
}
test<number>(123456) // 返回值是number类型的123456
test<string | boolean>('hahahaha') // 返回值是string类型的hahahaha
test<string | boolean>(false)

const test1 = <T>(arg: T): T => {
  console.log('泛型=', arg)
  return arg
}
const ret1 = test1<string>('Hello')
const ret2 = test1<number>(42)
const ret3 = test<number[]>([1, 2, 3])
  1. 在接口中使用泛型
javascript 复制代码
interface Search {
  <T, Y>(name: T, age: Y): T // 注意:这里写法是定义的方法哦。。。。。。
}

let fn: Search = function <T, Y>(name: T, id: Y): T {
  console.log(name, id)
  return name
}
fn('li', 11) // 编译器会自动识别传入的参数,将传入的参数的类型认为是泛型指定的类型

  1. 使用接口约束泛型
javascript 复制代码
interface Person {
 zname: string
 zage: number
}
function student<T extends Person>(arg: T): T {
 return arg
}
// 例子1:传入满足 Person 接口的对象
const person: Person = { zname: 'Alice', zage: 25 }
const result1 = student(person) // 返回类型为 Person

// 例子2:传入满足 Person 接口的子类型的对象
class Student implements Person {
 zname: string
 zage: number
 constructor(name: string, age: number) {
   this.zname = name
   this.zage = age
 }
}
const studentObj = new Student('Bob', 30)
const result2 = student(studentObj) // 返回类型为 Student

// 例子3:传入不满足 Person 接口的对象
const invalidObj = { zname: 'Charlie', zage: '20' } // 注意:zage 的类型错误
// const result3 = student(invalidObj); // 报错:类型 "{ zname: string; zage: string; }" 的参数不能赋给类型 "Person" 的参数

// 例子4:传入不满足 Person 接口的对象,但使用类型断言绕过类型检查
// const invalidObj2 = { zname: 'Charlie', zage: '20' } as Person; // 使用类型断言
// const result4 = student(invalidObj2); // 返回类型为 Person
相关推荐
森G4 小时前
TypeScript 基础类型
开发语言·typescript
烛阴12 小时前
用 MCP 调教 AI 代理:让 Cocos Creator 3.8.8 核心逻辑一键全自动生成
typescript·cocos creator
Rain50918 小时前
mini-cc 技术栈:跟着 Claude Code 先选 TypeScript + React + Ink
前端·javascript·react.js·typescript·node.js·ai编程
yantuguiguziPGJ19 小时前
WeMed:一个医疗垂直领域大模型 问答系统的 Taro 小程序
typescript·node.js
tedcloud1231 天前
wifi-densepose部署教程:构建无线人体感知系统
服务器·javascript·网络·typescript·ocr
奇奇怪怪的问题2 天前
学习ts笔记(二):属性修饰符,泛型,接口
前端·typescript
阿正的梦工坊2 天前
【Typescript】04-数组元组枚举与字面量类型
javascript·ubuntu·typescript
狼丶宇先森2 天前
vue-sign-canvas v2 重构复盘:从 Vue 2 签名板到 Vue 3 + TypeScript 组件库
前端·vue.js·重构·typescript·开源软件·canvas
muddjsv2 天前
前端开发语言使用流行度排行与分析
前端·javascript·typescript
Joy T2 天前
【Web3】Hardhat工程架构中Solidity与TypeChain的协作机制
git·架构·typescript·web3·智能合约·hardhat·typechain