当前位置:网站首页>typescript ts 基础知识之接口、泛型
typescript ts 基础知识之接口、泛型
2022-07-27 01:49:00 【糖糖246】
一、接口
接口用来定义一个对象结构,用来定义一个对象中应该包含哪些属性和方法
使用关键字 interface 定义
interface PersonObj{
name: string
age:number
}
const obj:PersonObj = {
name: '小明',
age: 18,
// gender: '男', //报错,gender没有在PersonObj中定义
}
1.接口也可以当成类型声明使用,同type
type MyType{
name: string,
age: number
}
const obj:MyType = { ... }
不同点:
type不能声明同一个名字的类型两次,会报错
type MyType{ ... }
type MyType{ ... } // 报错
接口interface可以声明同一个名字的类型两次,结果为两个声明合并,但后续声明中若有之前声明过的属性,则属性类型须一致
interface PersonObj{
name: string
age:number
}
interface PersonObj{
gender:string
}
const obj:PersonObj = {
name: '小明',
age: 18,
gender: '男'
}
2. 用类实现接口
接口可以在定义对象的时候限制对象的结构,接口中所有的属性都不能有实际的值,即接口只定义对象结构,不考虑实际值,类似于抽象类,不同的是在接口中所有的属性和方法都是抽象的,抽象类中可以有实质的属性和方法
定义类时,可以使类去实现一个接口(使类满足接口的要求),使用关键字implements
interface MyInter{
name:string
sayHi():void
}
class MyClass implements MyInter{
name:string
constructor(name:string){
this.name = name
}
sayHi(): void {
console.log('Hi~')
}
}
二、泛型
在定义函数或类时,遇到类型不明确的,可以使用泛型,泛型就是一个不确定的类型,调用时传入具体类型
1. 指定一个泛型
function fn<T>(a: T): T{ return a }
// 可以直接调用具有泛型的函数
fn(10) //不指定泛型,TS可以自动对类型进行推断
fn<string>('hello') //指定泛型
2. 指定多个泛型
function fn<T, K>(a:T, b:K):T{
return a
}
fn(10, 'hello')
fn<number,string>(10,'hello')
3. 限制泛型的范围
T extends Inter 表示泛型T 必须是Inter实现类(子类)
interface Inter{
length: number
}
function fn<T extends Inter>(a:T):number{
return a.length
}
fn('hello')
class MyClass<K>{
name: K
constructor(name: K){
this.name = name
}
}
const myClass = new MyClass<string>('a')
边栏推荐
- Volatile keyword and its function
- Worthington过氧化物酶活性的6种测定方法
- [机缘参悟-52]:交浅言深要因人而异
- Yilingsi T35 FPGA drives LVDS display screen
- C语言const用法详解
- impala 执行计划详解
- Deeply understand the underlying data structure and algorithm of MySQL index
- Portraiture5 new and upgraded leather filter plug-in artifact
- 快速排序及优化
- FactoryBean的getObject调用时机
猜你喜欢
随机推荐
Portraiture5 new and upgraded leather filter plug-in artifact
What are "full five unique" and "full two unique"? Any difference?
Code practice when the queue reaches the maximum length
How to design the red table of database to optimize the performance
Take you to know what Web3.0 is
Code review pyramid
Pytorch损失函数总结
The diagram of user login verification process is well written!
Spark Learning Notes (VI) -- spark core core programming RDD action operator
Best practices of opentelemetry in service grid architecture
图解用户登录验证流程,写得太好了!
spark:计算不同分区中相同key的平均值(入门级-简单实现)
Submodule cache cache failure
[learn FPGA programming from scratch -54]: high level chapter - FPGA development based on IP core - principle and configuration of PLL PLL IP core (Altera)
【flask】服务端获取客户端请求的文件
Boom 3D new 2022 audio enhancement app
PyCharm中Debug模式进行调试详解
带你了解什么是 Web3.0
数据库使用安全策略
MySQL的数据库有关操作









