Basic Types in TypeScript
TypeScript provides several basic types that are essential for building robust applications. These include number
, string
, boolean
, null
, and undefined
.
Let's create some simple applications to understand how to use these types effectively.
Problem 1 - Hello World
Thing to Learn: How to give types to function arguments.
Task: Write a function that greets a user given their first name.
Argument:
firstName
(string)Logs: "Hello {firstName}"
Return: None
Solution:
function greetUser(firstName: string): void {
console.log(`Hello ${firstName}`);
}
// Example usage:
greetUser('Alice');
Problem 2 - Sum Function
Thing to Learn: How to assign a return type to a function.
Task: Write a function that calculates the sum of two numbers.
Arguments:
a
(number),b
(number)Returns: Sum of
a
andb
(number)
Solution:
function sum(a: number, b: number): number {
return a + b;
}
// Example usage:
console.log(sum(5, 7)); // Output: 12
Problem 3 - Return True or False Based on Age
Thing to Learn: Type inference.
Task: Write a function that returns true if a user is 18 or older.
Function Name:
isLegal
Argument:
age
(number)Returns:
true
ifage
is 18 or older, otherwisefalse
(boolean)
Solution:
function isLegal(age: number): boolean {
return age >= 18;
}
// Example usage:
console.log(isLegal(20)); // Output: true
console.log(isLegal(17)); // Output: false
Problem 4 - Run a Function After 1 Second
Thing to Learn: How to handle functions as arguments.
Task: Create a function that takes another function as input and runs it after 1 second.
Function Name:
runAfterOneSecond
Argument:
fn
(function)Returns: None
Solution:
function runAfterOneSecond(fn: () => void): void {
setTimeout(fn, 1000);
}
// Example usage:
runAfterOneSecond(() => {
console.log('This runs after 1 second');
});
These examples illustrate the use of TypeScript's basic types and provide a foundation for understanding how to work with typed arguments, return types, and type inference in functions.
Last updated
Was this helpful?