In this example, we have a
greet function that takes a single parameter
name of type
string and returns nothing (
void). The syntax for specifying the type of a variable is done by adding a colon and the type right after the variable name, like
TypeScript comes with a range of built-in types that allow you to be specific about the data your functions and variables work with. Some of the most common types are:
string: Represents a sequence of characters, like
number: Represents a numeric value, like
boolean: Represents a true or false value.
Here's an example of using these basic types in TypeScript:
TypeScript provides more advanced types and type manipulation features, like:
- Arrays: Using the
syntax, you can create an array of a specific type, like
- Tuples: A tuple is a fixed-length array with specific types for each element.
- Enums: Enumerations allow you to define a set of named constants.
- Any: The
anytype is used when you don't know the type of a variable or when you want to opt out of type checking.
- Unknown: Similar to
unknowntype is used for values you don't know the types of, but with stricter type checking.
These are just a few examples of the many types and features TypeScript offers. As you dive deeper into TypeScript, you'll discover more advanced types like
type alias, and utility types that help you model your application in a safe and flexible way.