Introduction
In this tutorial, we’ll create a basic TypeScript program that identifies and prints vowels from a given string. TypeScript, a strongly-typed superset of JavaScript, provides robust tools for type safety and code clarity. By the end of this guide, you’ll understand how to manipulate strings and arrays in TypeScript to extract specific characters, in this case, vowels.
Code Explanation
Below is a simple TypeScript program that prints all vowels from a given string. We’ll break down each step of the program to explain how it works.
TYPESCRIPT CODE
// Function to print vowels from a given string
function printVowels(input: string): void {
// Define a string containing all vowels
const vowels: string = 'aeiouAEIOU';
// Initialize an empty string to store found vowels
let result: string = '';
// Iterate through each character in the input string
for (let char of input) {
// Check if the character is a vowel
if (vowels.includes(char)) {
// Add the vowel to the result string
result += char;
}
}
// Print the result string containing only vowels
console.log('Vowels in the string:', result);
}
// Example usage
const exampleString: string = 'Hello, TypeScript World!';
printVowels(exampleString);
TypeScriptExplanation of Each Step
Define the Function:
function printVowels(input: string): void {
TypeScriptInitialize Vowels String:
const vowels: string = 'aeiouAEIOU';
TypeScriptInitialize Result String:
let result: string = '';
TypeScriptIterate Through the Input String:
for (let char of input) {
TypeScriptCheck for Vowel:
if (vowels.includes(char)) {
TypeScriptAppend Vowel to Result:
result += char;
TypeScriptPrint the Result:
console.log('Vowels in the string:', result);
TypeScriptExample Usage:
const exampleString: string = 'Hello, TypeScript World!';
printVowels(exampleString);
TypeScriptOutput
When you run the above TypeScript code with the example string 'Hello, TypeScript World!'
, the output will be:
Vowels in the string: eooieio
TypeScriptConclusion
In this guide, we wrote a simple TypeScript program to print vowels from a string. We explored how to define functions, work with strings, and use basic control structures like loops and conditionals. This example showcases the fundamental aspects of TypeScript while providing a clear and practical application. With this knowledge, you can now experiment with other string manipulations and continue to enhance your TypeScript skills.
For further learning, you can explore the official TypeScript documentation to deepen your understanding of TypeScript’s capabilities.