typescript之模块开发
dearweb
发布:2021-07-31 15:33:47阅读:
定义在一个模块里的变量、函数、类等等在模块外部是不可见的,除非你明确的使用export形式导出他们。相反,如果先使用其它模块导出变量、函数、类、接口等的时候,你必须要导入它们,可以使用import形式之一。
小编对于模块化的理解:
可以把一些公共的功能单独抽离成一个文件作为一个模块。模块里面的变量函数类等认为是私有的,如果我们要在外部访问模块里面的数据(变量、函数、类),我们需要通过export暴露模块里面的数据(变量、函数、类...),暴露后通过import引入模块就可以使用模块里面暴露的数据(变量、函数、类...)。
目录结构

db.ts代码
interface DBI<T>{
add(info:T):boolean;
update(info:T,id:number):boolean;
delete(id:number):boolean;
get(id:number):any[];
}
// 定义一个操作Mysql的数据库的类 注意:要实现泛类型接口 这个类也应该是一个泛类型
export class MysqlDb<T> implements DBI<T> {
add(info: T): boolean {
console.log(info)
return true
throw new Error("Method not implemented.")
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.")
}
delete(id: number): boolean {
throw new Error("Method not implemented.")
}
get(id: number): any[] {
throw new Error("Method not implemented.")
}
}
// 定义一个操作mssql的数据库的类
export class MssqlDb<T> implements DBI<T> {
add(info: T): boolean {
throw new Error("Method not implemented.")
}
update(info: T, id: number): boolean {
throw new Error("Method not implemented.")
}
delete(id: number): boolean {
throw new Error("Method not implemented.")
}
get(id: number): any[] {
throw new Error("Method not implemented.")
}
}index.ts代码
import {MysqlDb} from './modules/db'
class User {
username:string | undefined
password:string | undefined
}
let U = new User()
U.username = '李四'
U.password = '12345678'
let oMysql = new MysqlDb<User>();
oMysql.add(U) // {username: "李四", password: "12345678"}最后在中端执行一下 node index 输出为
User { username: '李四', password: '12345678' }小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧