When you work with union types, typing them can be tedious. For example, every time writing string | number
and... makes the code crowded. To solve this problem, you can write a type that holds your union type (something like a variable for types). This holder is called alias. To do this, you must use the type
keyword and then write your chosen name. Example:
type Combinable = number;
The combinable
name is based on my personal taste and you can choose any other name for it. If you pay attention, doing such a thing (the above code) is not very wise, because instead of writing a number, we have now defined an alias and the codes are unnecessarily crowded. This is the reason why they are not usually used to save a type and we use them when we need union types. For example:
type Combinable = number | string;
Pay attention to the following code:
function combine(
input1: number | string,
input2: number | string,
resultConversion: 'as-number' | 'as-text'
) {
let result;
if (typeof input1 === 'number' && typeof input2 === 'number' || resultConversion === 'as-number') {
result = +input1 + +input2;
} else {
result = input1.toString() + input2.toString();
}
return result;
}
Now we can simplify the code of this function and instead of number | string
only mention the combinable
value:
function combine(
input1: Combinable,
input2: Combinable,
We can also define a new alias for the literal type we defined in this function (as-number
and as-text
):
type ConversionDescriptor = 'as-number' | 'as-text';
Now we place this alias in the function:
type Combinable = number | string;
type ConversionDescriptor = 'as-number' | 'as-text';
function combine(
input1: Combinable,
input2: Combinable,
resultConversion: ConversionDescriptor
) {
let result;
// Other Codes ... //
Their power may not be seen so much in a simple function, but if you work in a real program, you will notice that the number of union types increases greatly and the ability to use them in the form of alias makes the code much simpler.
You should also know that you are not limited to union types and literal types in using them. For example, when we want to define the type of some objects manually, we can act as follows:
type User = { name: string; age: number };
const u1: User = { name: 'Max', age: 30 };
In this way, you can avoid unnecessary repetitions. Another example is the following code, which is a little complicated due to the addition of types:
function greet(user: { name: string; age: number }) {
console.log('Hi, I am ' + user.name);
}
function isOlder(user: { name: string; age: number }, checkAge: number) {
return checkAge > user.age;
}
We can easily simplify these functions with the help of aliases:
type User = { name: string; age: number };
function greet(user: User) {
console.log('Hi, I am ' + user.name);
}
function isOlder(user: User, checkAge: number) {
return checkAge > user.age;
}
return types in functions (Void
and undefined
type)
So far we've learned about specifying types for function input parameters, but you can do more with functions. For example, consider the following function:
function add(n1: number, n2: number) {
return n1 + n2;
}
In addition to the types of input parameters, this function can take another type called return type. If you hover your mouse over add, you'll see this type guessed by TypeScript:
The type written after the colon is the return type or the type of output value from the function. In the same way, we can define this type:
function add(n1: number, n2: number): number {
return n1 + n2;
}
As you can see, this type comes with a colon after the parameters. As long as you don't have a specific reason to specify this type manually, it is better to let the typescript define this type by itself, like variables.
Of course, there is a new type for working with return types that I have not discussed before. The name of this type is void
. For example, consider this new function:
function add(n1: number, n2: number): number {
return n1 + n2;
}
function printResult(num: number): void {
console.log('Result: ' + num);
}
This function receives a number and returns this number along with a string. Now if we call it as follows:
printResult(add(5, 12));
That is, I have given the add
function as a parameter to the printResult
function. If we run this code, we see the following output in the browser console, which is also correct:
Result: 17
There is another type in TypeScript that is very similar to void
and we call it undefined
. In fact, the difference between the two is very small. When a function does not have a return
statement, its type is void
, but if we leave the type of a function undefined
, it means that it has a return
statement but does not return anything, like this function:
function printRST(num: number): undefined {
console.log('Result: ' + num);
return;
}
Of course, in practice, the above function is no different from the following function:
function printRST(num: number): void {
console.log('Result: ' + num);
}
But TypeScript makes a technical difference between them in order to be more precise. In the real world of programming, we almost never use undefined
because it is not very useful and is only used in very special cases.
Hello,
this Comment has been upvoted with 100%, thanks to @albro who burned 1000 PLANET
With this burn @albro is actively participating in the CLEAN PLANET reward protocol.
@albro is helping @cleanplanet to grow with the curation.
Thanks for your help
@cleanplanet
Congratulations!
✅ Good job. Your post has been appreciated and has received support from CHESS BROTHERS ♔ 💪
♟ We invite you to use our hashtag #chessbrothers and learn more about us.
♟♟ You can also reach us on our Discord server and promote your posts there.
♟♟♟ Consider joining our curation trail so we work as a team and you get rewards automatically.
♞♟ Check out our @chessbrotherspro account to learn about the curation process carried out daily by our team.
🥇 If you want to earn profits with your HP delegation and support our project, we invite you to join the Master Investor plan. Here you can learn how to do it.
Kindly
The CHESS BROTHERS team
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support.