We already looked at the very first script in TypeScript, but it buys us nothing new. So let’s look at how we can use typed variables, and how it will stop errors, on a simple scale.
So if we want to expand on our first example, we might want to use a variable.
let helloWorld = "Hello World";
Now TypeScript can infer variable types in many cases, just like JavaScript can. So in this case, we can clearly see that helloWorld will be of type string.
But you can also explicitly state it:
let helloWorld:string = "Hello World";
Here we use the colon (:) after the variable name to explicitly tell TypeScript that it will be a string
. If you try to give it a data-type that is incorrect, it will give you an error like you see here:
When we add these two things together, we can have:
let helloWorld:string = "Hello World";
console.log(helloWorld);
This obviously is still a simple application. So let see how else we can assign data types.
Assigning Data Types in Function Parameters
When we define our function’s parameters, we can specify a type after our parameter name. This is just as we would do define a type for a variable as seen in our previous example. This means something like the following in JavaScript, would be written like so in TypeScript:
// example in JavaScript
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
// example in TypeScript
function fullName(firstName:string, lastName:string) {
return firstName + " " + lastName;
}
Notice how similar it is to how we defined a parameter normally.
Returning Typed Results from a Function
Of course, we don’t want to limit ourselves to only passing typed values. We want to make sure data returned from a function is correct as well. Therefore, we can specify the type of data that is to be returned.
In our previous function, you can see how we want to return data as well. Now, in normal circumstances, we should logically expect the data returned to be a string, however, we have no way of enforcing that, or making sure the data is put into a string in JavaScript. So TypeScript will allow us to put the type after the function name and parameters, similar to how we can optionally do it in Python.
// example of a function returning a string
function fullName(firstName:string, lastName:string) :string {
return firstName + " " + lastName;
}
We can then call it within a function where we expect a string, using it to define a new string, etc. However, we’ll get an error if we try to put that value from our function into a variable with a different type.
// both of these are valid in TypeScript
let fName = fullName("John", "Smith"); // fname is not typed
let fName2:string = fullName("John", "Smith"); // fname2 is typed
// this gives an error however
// Type 'string' is not assignable to type 'number'
let value:number = fullName("John", "Smith");
Typed and Non-Typed
Notice in our previous example, we can have typed variables, however, we don’t have to. This, however, can cause one to wonder why you would use TypeScript, if you don’t use types? There are times you want a variable data type, however, in most cases you don’t need or see them.
TypeScript Types
Because TypeScript sits on top of JavaScript, it is limited to most of the data types JavaScript is going to provide internally. We’ve seen some previously, and you can look back to see some of the common JavaScript data types.
Here are some examples of data types you might use with TypeScript.
Data Type | Description | Example Values |
---|---|---|
number | Numeric values, including integers and floating-point numbers | 42 , 3.14 , -0.5 , 1e3 |
string | Textual data | "hello" , 'world' , \ template string“ |
boolean | True or false values | true , false |
null | Represents an empty or non-existent value | null |
undefined | Represents an uninitialized variable | undefined |
bigint | Large integers | 123n , 9007199254740991n |
symbol | Unique values, typically for object keys | Symbol("id") , Symbol("key") |
array | A collection of values of the same type | [1, 2, 3] , ["a", "b", "c"] , [true, false] |
tuple | A fixed-length array with specified types for each element | [string, number] → ["John", 30] |
object | Collection of key-value pairs, used to represent structured data | { name: "Alice", age: 25 } |
enum | Defines a set of named constants | enum Direction { Up, Down, Left, Right } |
any | Allows any type of value | 42 , "hello" , true , {} , etc. |
void | Represents no value, typically used for functions that do not return anything | Function return type: void |
unknown | Similar to any , but safer, as you must check type before use | Value assigned to unknown variable can be of any type |
never | Represents a value that never occurs, such as in functions that throw errors or have infinite loops | function throwError(): never { throw new Error("Error") } |
If you want to see them in code, here is some examples:
let age: number = 30;
let name: string = "Alice";
let isActive: boolean = true;
let items: string[] = ["apple", "banana"];
let person: { name: string; age: number } = { name: "Bob", age: 40 };
let direction: Direction = Direction.Up; // enum Direction { Up, Down, Left, Right }
let id: symbol = Symbol("id");
let result: any = "Could be anything";
let unknownValue: unknown = 42;
Of course, you can also create your own data types as well. We’ll see how to do that next.
Writing Our First TypeScript was originally found on Access 2 Learn
2 Comments
Comments are closed.