首页 Order Typescript 正文

Typescript 泛型

金鹏头像 金鹏 Typescript 2024-10-07 11:10:40 0 248
导读:泛型允许我们在定义函数、类或接口时,使用类型参数来表示未指定的类型,这些参数在具体使用时,才被指定具体的类型,泛型能让同一段代码适用于多种类型,同时仍然保持类型的安全性。举例:如下...

泛型允许我们在定义函数、类或接口时,使用类型参数来表示未指定的类型,这些参数在具体使用时,才被指定具体的类型,泛型能让同一段代码适用于多种类型,同时仍然保持类型的安全性。


举例:如下代码中<T>就是泛型,(不一定非叫T),设置泛型后即可在函数中使用T来表示该类型:

function logData<T>(data: T): T {


  console.log(data)


  return data


}



logData<number>(100)


logData<string>('hello')


function logData<T, U>(data1: T, data2: U): T | U {


  console.log(data1,data2)


  return Date.now() % 2 ? data1 : data2


}



logData<number, string>(100, 'hello')


logData<string, boolean>('ok', false)


interface PersonInterface<T> {


  name: string,


  age: number,


  extraInfo: T


}



let p1: PersonInterface<string>


let p2: PersonInterface<number>



p1 = { name: '张三', age: 18, extraInfo: '一个好人' }


p2 = { name: '李四', age: 18, extraInfo: 250 }


interface LengthInterface {


  length: number


}



// 约束规则是:传入的类型T必须具有 length 属性

function logPerson<T extends LengthInterface>(data: T): void {


  console.log(data.length)


}



logPerson<string>('hello')


// 报错:因为number不具备length属性

// logPerson<number>(100)

class Person<T> {


  constructor(


    public name: string,


    public age: number,


    public extraInfo: T


  ) { }


  speak() {


    console.log(`我叫${this.name}今年${this.age}岁了`)


    console.log(this.extraInfo)


  }


}



// 测试代码1

const p1 = new Person<number>("tom", 30, 250);



// 测试代码2

type JobInfo = {


  title: string;


  company: string;


}


const p2 = new Person<JobInfo>("tom", 30, { title: '研发总监', company: '发发发科技公司' });



类型声明文件

类型声明文件是 TypeScript 中的一种特殊文件,通常以.d.ts 作为扩展名。它的主要作用是为现有的 JavaScript 代码提供类型信息,使得 TypeScript 能够在使用这些 JavaScript 库或模块时进行类型检查和提示。 


export function add(a, b) {


  return a + b;


}



export function mul(a, b) {


  return a * b;


}



declare function add(a: number, b: number): number;


declare function mul(a: number, b: number): number;



export { add, mul };


// example.ts


import { add, mul } from "./demo.js";



const x = add(2, 3); // x 类型为 number


const y = mul(4, 5); // y 类型为 number



console.log(x,y) 



本文地址:https://www.jinpeng.work/?id=226
若非特殊说明,文章均属本站原创,转载请注明原链接。
广告3

欢迎 发表评论:

  • 请填写验证码

日历

«    2025年4月    »
123456
78910111213
14151617181920
21222324252627
282930

控制面板

您好,欢迎到访网站!
  查看权限
广告2

退出请按Esc键