本文主要是介绍TypeScript学习日志-第二十二天(Mixins混入),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Mixins混入
一、对象混入 合并
当我们有两个或多个对象的时候,如何将这两个对象合并,如图:
interface A {name:string
}
interface B {age:number
}
let a:A = {name:'小明'
}
let b:B = {age:10
}
// 1.扩展运算符 浅拷贝 返回新的类型
let c = {...a,...b}
// 2.ES6 Object.assign 浅拷贝 交叉类型
let c2 = Object.assign({},a,b)
二、类的混入
// 插件类型的混入
class Logger {log(msg:string){console.log(msg)}
}class Html {render(){console.log('render')}
}class App {run(){console.log('run')}
}
type Custructor<T> = new (...args:any[]) => T
function pluginMinxins <T extends Custructor<App>>(Base:T){return class extends Base {private Logger = new Logger()private Html = new Html()constructor(...args:any[]){super(...args)this.Logger = new Logger()this.Html = new Html()}run () {this.Logger.log('run')}render(){this.Logger.log('run')this.Html.render()}}
}const mixins = pluginMinxins(App)
const app = new mixins()
app.run()
app.render()
这篇关于TypeScript学习日志-第二十二天(Mixins混入)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!