To define a User class in order to map the database
To define a MysqlDb 'class' in order to operate the database
To pass the User class into MysqlDb as parameters
class User{
username: string | undefined;
password: string | undefined;
}
class MysqlDb{
add(user: User): boolean{
console.log(user);
return true;
}
}
var u = new User( );
u.username = 'shawn';
u.password = 1234;
var Db = new MysqlDb ( );
Db.add(u); // password: 1234, username: 'shawn'
If above case we would like to apply with other class, then MysqlDb would need to redefine again, therefore, here it is easier if we use Generic , then we could define different User class, but only with one MysqlDb class would be enough for managing all the data.
Notice here when the Db is defined, User needs to be put as a constrain, in order better using MysqlDb, otherwise, any type of Data would be able to pass into the MysqlDb.
class User{
username: string | undefined;
password: string | undefined;
}
var u = new User( );
// 1. method to add data
u.username = 'shawn';
u.password = 1234;
var Db = new MysqlDb<User> ( );
Db.add(u); // password: 1234, username: 'shawn'
*********
class ArticleCate{
title: string | undefined;
desc: string | undefined;
status: number | undefined;
// 2. method to add data
// here using constructor to constain the instance must have these parameters.
// if any parametere does not need to be used in the instance,
// then it should have a `?` before `:` inside the constructor definition
constructor( params:{
title: string | undefined,
desc: string | undefined,
status?: number | undefined,
}){
this.title = params.title;
this.desc = params.desc;
this.status = params.status;
}
}
var a = new ArticleCate({
title : 'This is title',
desc: 'This is Desc',
});
var Db2 = new MysqlDb<ArticleCate>( );
Db2.add(a);
Here we have an example,
class
in order to map the databaseIf above case we would like to apply with other class, then
MysqlDb
would need to redefine again, therefore, here it is easier if we useGeneric
, then we could define different User class, but only with one MysqlDb class would be enough for managing all the data.Notice here when the Db is defined,
User
needs to be put as a constrain, in order better using MysqlDb, otherwise, any type of Data would be able to pass into the MysqlDb.