In this post, we will see how to use Generics and Modules in TypeScript.
GENERICS
function AddNumber(val1: number, val2:number): string{
return `${val1}+${val2}`;
}
function AddString(val1: string, val2:string): string{
return `${val1}+${val2}`;
}
console.log(AddNumber(5,5));
console.log(AddString('Hello', 'world'));
If we run the script, this will be the result:
Now, using Generics, we will optimise the code:
function AddGeneric<T>(val1:T, val2:T): string{
let result = `${val1}+${val2}`;
return result;
}
console.log(AddGeneric(25,5));
console.log(AddGeneric('Damiano', 'Abballe'));
If we run the script, this will be the result:
MODULES
In TypeScript, a module is a file containing values, functions, or classes that we can make public in order to use them in other files.
[USER.TS]
// using the key "export", we will be able to
// use this class in another file
export class User{
_username: string;
_password: string;
constructor(username: string, password: string)
{
this._username = username;
this._password = password;
}
DisplayInfo(): string{
return `Hello ${this._username}! Your password is ${this._password}`;
}
}
[CORE.TS]
// using the key "import" we will be able to use the external file user.js
import { User } from './user.js';
const objUser = new User('UserName', 'Password');
// we get the HTML input element with the Id = txtInput
const inputEle = document.querySelector('#txtInput') as HTMLInputElement;
// we will show the user's info in the input element
inputEle.value= objUser.DisplayInfo();
[INDEX.HTML]
<html>
<head></head>
<body>
<input type="text" id="txtInput" value="pippo" style="width: 300px;">
<!-- we have to insert 'module', because in core.js we use an external module -->
<script type="module" src='core.js'></script>
</body>
</html>
Now, if we compile the file and we open the index.html with a browser, this will be the result: