首页 > 其他分享 >TS泛型

TS泛型

时间:2022-12-19 15:44:52浏览次数:27  
标签:string class TS public 泛型 check name

有人疑惑:为什么使用泛型呢,使用any不好吗?从使用方面来讲,any是可以运行的!但是遇到如下的情况就必须使用泛型:教务系统中对学校人员进行年审一个function,既需要处理student类,teacher类,也需要处理manager类,这三个类均继承自person的父类,处理哪个类实体返回哪个类实体,而使用any,显然不安全!

把泛型用在方法上

class Person {}
class Student extends Person{
    constructor(public name:string,public age:number,public check:boolean){
        super()
    }
}
class Teacher extends Person{
    constructor(public name:string,public age:number,public check:boolean){
        super()
    }
}
/**
 * 这里仅举例,不做任何业务操作
 * */
function check<T>(personal:T):T {
    return personal
}
let jack = check(new Student('jack',18,true))
let alice = check(new Teacher('alice',48,false))

当然,写代码开发时候还可以再严谨些

标签:string,class,TS,public,泛型,check,name
From: https://www.cnblogs.com/JarryShu/p/16992325.html

相关文章

  • [LeetCode] 1971. Find if Path Exists in Graph
    Thereisa bi-directional graphwith n vertices,whereeachvertexislabeledfrom 0 to n-1 (inclusive).Theedgesinthegrapharerepresentedasa......
  • lightdb extra_float_digits--控制浮点数精度
    lightdb中extra_float_digits参数可以用来控制浮点数输出的精度,其采用原生c语言的float4/float8实现,可能我们在平时使用中并不太会留意,但是显示的时候会有一些问题。建一......
  • echarts警告、css元素隐藏
    在页面渲染的时候,控制台有时候会出现  Thereisachartinstancealreadyinitializedonthedom  的警告,这种原因是因为echarts的dom已经存在。解决方法:在加载ec......
  • delphi D11编程语言手册 学习笔记(P424-477) 泛型
      这本书可以在Delphi研习社②群256456744的群文件里找到.书名:Delphi11AlexandriaEdition.pdf 泛型在C++中叫做类型模板(templateclasses),单从字面上理......
  • saltstack学习
    salt-master:[root@salt-master~]#systemctl stop  firewalld [root@salt-master~]#systemctl  disable  firewalld [root@salt-master~]#sed -i......
  • JDBC之Statement和ResultSet
    Statement和ResultSet目录Statement和ResultSetStatementStatement概述要执行的SQL分为两类查询增删改Statement继承体系SQL注入问题SQL注入问题解决ResultSet单值多值重......
  • vue3+ts项目中无法识别vue文件
    在vue3+ts的项目中,如果缺少声明文件,会出现类似于下面的报错。只需要在src的根目录下创建一个声明文件:env.d.ts,就可以解决这个报错。代码内容如下:declaremodule"*.......
  • cppconn resultsetmetadata get columns count,get column name,resultset get value
    //Model/mysqlhelper.h#ifndef__mysqlhelper_h__#define__mysqlhelper_h__#include<chrono>#include<ctime>#include<fstream>#include<iomanip>#include<i......
  • windows10 netsh wlan命令连接新wifi
    通过修改已存在的profile的ssid和密码来连接新的wifi。1. 查看当前存在的profile(本机连接过的wifi会生成一个profile)netshwlanshowprofilesUserprofiles------......
  • 使用 DirectSound 录制麦克风音频
    使用DirectSound录制麦克风音频本文所有代码均可在以下仓库找到https://gitcode.net/PeaZomboss/learnaudios目录是demo/dscapture之前那篇文章简单介绍了DirectSoun......