- 接口的多态,同一个方法,传入不同的参数,他所对应的操作不同成为多态【参数不同】
- 或者可以理解为同一个方法,返回不同的结果,称之多态。
interface IfnPerson {
run():void
run(id:number):void
run(id:number,name:string):void
}
class Person implements IfnPerson{
run():void
run(id:number):void
run(id:number,name:string):void
run(id?:number,name?:string):void{
console.log(id,name);
}
}
const p = new Person();
p.run()
p.run(12)
p.run(12,"wwqiew")
interface IfnPerson {
run():void
run(id:number):void
run(id:number,name:string):void
}
class Person implements IfnPerson{
run():void
run(id:number):void
run(id:number,name:string):void
run(id?:number,name?:string):void|string|number{
if(arguments.length===0){
return "没有参数"
}else if(id as number>0 && name === undefined){
return id;
}else{
return id as number+<string>name
}
}
}
const p = new Person();
p.run()
p.run(12)
console.log(p.run(12,"wwqiew"));
泛型:宽泛的类型,在定义时指占位,不确定类型,在调用时才给定类型。
定义一个函数或类时,在定义时还无法确定它参数或返回值是什么类型,这时可以用any或unknown来解决,当然也可以使用泛型定占位。
参数是任意类型,返回也是任意类型来规避,ts的类型检查。
function fn(arg:any):any{
console.log(arg);
return arg
}
fn(1)
fn("wqw")
fn(false)
泛型函数
在定义时不指定类型,返回时指定类型;
function fn<T>(arg:T):T{
console.log(arg);
return arg
}
fn<string>("1")
fn<Array<string>>(["1","ok"])
实例化类——的函数
function fn<T>(classname:{
new():T}){
return new classname();
}
//箭头函数写法
//const fn = <T>(classname:{new() :T}):T=>new classname()
class A{
}
class B{
}
// 类也可以作为类型
let a = fn<A>(A);
let b = fn<B>(B);
泛型类型限制
定义一个泛型 类。
class User<T>{
private useList:T[] = []
push = (value:T)=>{
this.useList.push(value)
}
}
let user = new User<string>();
user.push("a")
console.log(user);
//用接口来规范泛型类
interface Ic{
id:number,
name:string
}
let user = new User<Ic>()
user.push({
id:1,name:"niuniu"})
console.log(user);
泛型是可以多个的。多个以逗号隔开。
class User<T,K>{
name!:T;
age!:K;
constructor(name:T,age:K){
this.age = age;
this.name = name;
}
}
let user =new User("niuniu",25)
泛型也可以限制类型。
当前的T类型中一定要与在extends指定的父类型(接口)中得有此属性,没有那就嗝屁。
interface Ic{
length:number
}
function test<T extends Ic>(arg:T){
console.log(arg.length);
return arg.length
}
test({
length:123})
test<string>("wqewq")
test<number[]>([1,2])
// 条件交换
type Excludetype<T,K> = T extends K ? never:T
// 类型的范围限制
type Test = Excludetype<object|string,string|number|boolean>
泛型默认值
function test<T = number>(arg:T):number{
return (arg as unknown as string).length
}
// 可以不写为自动类型
test("1")
class Person<T=string,k=number>{
name!:T
age!:k
}
const p = new Person()
泛型接口
定义接口时,没有指定类型。
声明的时候去指定类型
interface Isum<T,K>{
(a:T,b:K):void
}
const fn:Isum<number,string> = (a:number,b:string)=>{
console.log(a,b);
}
或者
给函数使用,在调用时给定类型
interface Isum{
<T,K>(a:T,b:K):void
}
const fn:Isum = <T,K>(a:T,b:K):void=>{
console.log(a,b);
}
fn<number,string>(1,"2")
函数的协变和逆变
函数中返回值就是协变,函数形参就是逆变。
协变:类型是自己或子类
逆变:类型是自己或父类