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:
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:
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:
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:
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?