Basic Syntax
Variables
TypeScript is a programming language that is a superset of JavaScript, meaning that it includes all of the capabilities of JavaScript but also adds some additional features. One of these features is the ability to specify the type of a variable when it is declared.
In JavaScript, variables are declared using the
In JavaScript, variables are declared using the
let
keyword, and the type of the variable is determined by the value that is assigned to it. For example:let x = 5; // x is a number
let y = "hello"; // y is a string
You can specify the type of a variable when it is declared by using a colon (:) after the variable name, followed by the type. For example:
let x: number = 5; // x is a number
let y: string = "hello"; // y is a string
By specifying the type of a variable, you can catch errors at compile time (i.e., before the code is run) that would otherwise only be caught at runtime. For example, if you try to assign a string value to a variable that has been declared as a number, you will get a compile-time error in TypeScript but not in JavaScript.
let x: number = 5; // x is a number
x = "hello"; // error: Type 'string' is not assignable to type 'number'
Overall, the added syntax in TypeScript for declaring variables allows for stronger type checking and can help prevent errors in your code.
Functions
In addition to allowing you to specify the type of a variable when it is declared, TypeScript also provides syntax for specifying the types of function parameters and return values. This can help catch errors and make your code more readable and easier to understand.
In JavaScript, functions are declared using the
In JavaScript, functions are declared using the
function
keyword, and the types of the function parameters and return values are not specified. For example:function add(x, y) {
return x + y;
}
You can specify the types of a function’s parameters and return value by using a colon (:) after the parameter name, followed by the type. For example:
function add(x: number, y: number): number {
return x + y;
}
In the above example, the
add
function takes two parameters, x
and y
, which are both numbers, and it returns a value of type number
. If you try to call the add
function with arguments that are not numbers, you will get a compile-time error in TypeScript but not in JavaScript.add(5, "hello"); // error: Argument of type '"hello"' is not assignable to parameter of type 'number'.
Overall, the added syntax in TypeScript for declaring functions allows for stronger type checking and can make your code more readable and maintainable.