TypeScript Basic Syntax

A TypeScript program consists of the following parts:

  • Modules
  • Functions
  • Variables
  • Statements and Expressions
  • Comments

First TypeScript Program

We can use the following TypeScript program to output "Hello World":

Example.ts file code:

const hello : string = "Hello World!" console.log(hello)

Try it »

The above code is first compiled via thetsccommand:

tsc Example.ts

The following js code is obtained:

Example.js file code:

var hello = "Hello World!"; console.log(hello);

Finally, we use the node command to execute this js code.

$ node Example.js
Hello World

The whole process is shown in the following figure:

We can compile multiple ts files at the same time:

tsc file1.ts file2.ts file3.ts

The commonly used compilation parameters of tsc are shown in the following table:

No. Compilation parameter description
1.

--help

Display help information

2.

--module

Load extension modules

3.

--target

Set ECMA version

4.

--declaration

Additionally generate a file with the .d.ts extension.

tsc ts-hw.ts --declaration

The above command will generate two files: ts-hw.d.ts and ts-hw.js.

5.

--removeComments

Remove comments from files

6.

--out

Compile multiple files and merge them into one output file

7.

--sourcemap

Generate a sourcemap (.map) file.

A sourcemap is an information file that stores the mapping of corresponding positions between source code and compiled code.

8.

--module noImplicitAny

Report an error when there is an implicit any type on expressions and declarations.

9.

--watch

Run the compiler in watch mode. It will watch the output files and recompile when they change.


TypeScript Reserved Keywords

The TypeScript reserved keywords are shown in the following table:

KeywordDescription
abstractUsed to define abstract classes or abstract methods.
anyRepresents the any type, disabling type checking.
asType assertion, used to convert one type to another.
awaitUsed in async functions to pause code execution until the Promise resolves.
booleanRepresents the boolean type.
breakExits a loop or a switch statement.
caseUsed for branches in a switch statement.
catchUsed to catch exceptions.
classUsed to define a class.
constDefines a constant variable.
continueSkips the current loop iteration and continues with the next one.
debuggerStarts the debugger and pauses code execution.
declareDeclares a variable or module, usually used in type declaration files.
defaultDefines the default branch of a switch statement.
deleteDeletes an object's property or an array's element.
doUsed indo...whileloops.
elseDefines the else part in a conditional statement.
enumDefines an enum type.
exportUsed to export variables, functions, or classes from a module.
extendsUsed for class inheritance, indicating that a class inherits from another class.
falseBoolean valuefalse。
finallyDefinestry...catchthe final execution code block in the statement.
forUsed inforloops.
fromUsed in module import statements to specify the source of the module.
functionDefines a function.
getUsed for an object's getter method.
ifUsed for conditional judgment.
implementsUsed for a class to implement an interface.
importUsed to import content from a module.
inUsed to check whether an object contains a specified property, or used infor...inloops.
inferUsed to infer types in conditional types.
instanceofChecks whether an object is an instance of the specified class.
interfaceUsed to define an interface.
letDefines a block-scoped variable.
moduleDefines a module (used in earlier versions of TypeScript).
namespaceDefines a namespace (used in earlier versions of TypeScript).
newCreates an instance of a class.
nullRepresents a null value.
numberRepresents the number type.
objectRepresents a non-primitive type.
ofUsed infor...ofloops.
packageUsed in the module system to identify packages.
privateUsed as an access modifier for class members, indicating private.
protectedUsed as an access modifier for class members, indicating protected.
publicUsed as an access modifier for class members, indicating public.
readonlyIndicates a read-only property.
requireUsed to import CommonJS modules.
returnExits a function and can return a value.
setUsed for an object's setter method.
stringRepresents the string type.
superUsed to call a parent class's method or constructor.
switchUsed in switch statements.
symbolRepresents the symbol type.
thisRefers to the instance of the current class or object.
throwThrows an exception.
tryUsed in exception handling statementstry...catch。
trueBoolean valuetrue。
typeUsed to define a type alias.
typeofGets the type of a variable or expression.
undefinedRepresents an undefined value.
uniqueUsed forsymbolthe unique identifier of the type.
varUsed to declare variables (no longer recommended).
voidRepresents the type with no return value.
whileUsed inwhileloops.
withUsed to create a scope in which references to the object can be omitted (not recommended).
yieldUsed in generator functions to pause and resume the execution of the generator.

Whitespace and Line Breaks

TypeScript ignores spaces, tabs, and line breaks that appear in a program.

Spaces and tabs are usually used to indent code, making it easier to read and understand.

TypeScript is Case-Sensitive

TypeScript distinguishes between uppercase and lowercase characters.

Semicolons are Optional

Each line of instructions is a statement. You can use semicolons or not. Semicolons are optional in TypeScript, but they are recommended.

The following code is all valid:

console.log("Example")
console.log("Google");

If statements are written on the same line, semicolons must be used to separate them, otherwise an error will be reported, for example:

console.log("Example");console.log("Google");

TypeScript Comments

Commenting is a good habit. Although many programmers hate comments, it is still recommended that you write textual explanations in each piece of code.

Comments can improve the readability of a program.

Comments can contain some information about the program, such as the author of the code, descriptions of functions, etc.

The compiler will ignore comments.

TypeScript supports two types of comments

  • Single-line comments ( // )− The text after // is comment content.

  • Multi-line comments (/* */)− This type of comment can span multiple lines.

Comment examples:

// This is a single-line comment
 
/* 
 This is a multi-line comment 
 This is a multi-line comment 
 This is a multi-line comment 
*/

TypeScript and Object-Oriented Programming

Object-oriented programming is a method of understanding and abstracting the real world.

TypeScript is an object-oriented programming language.

Object-oriented programming mainly has two concepts: objects and classes.

  • Object: An object is an instance of a class (object does not mean finding a girlfriend), it has state and behavior. For example, a dog is an object. Its states include: color, name, breed; its behaviors include: wagging tail, barking, eating, etc.
  • Class: A class is a template that describes the behavior and state of a class of objects.
  • Method: A method is the implementation steps of the operations of a class.

In the figure below,girl、boyis the class, and each specific person is an object of that class:

TypeScript object-oriented programming example:

class Site { name():void { console.log("Example") } } var obj = new Site(); obj.name();

The above example defines a class Site, which has a method name(). This method outputs the string Example in the terminal.

The `new` keyword creates an object of the class, and this object calls the method name().

The generated JavaScript code after compilation is as follows:

var Site = /** @class */ (function () { function Site() { } Site.prototype.name = function () { console.log("Example"); }; return Site; }()); var obj = new Site(); obj.name();

Executing the above JavaScript code produces the following output:

Example
Other Extensions