Home  >  Article  >  Web Front-end  >  Getting Started with TypeScript

Getting Started with TypeScript

藏色散人
藏色散人Original
2019-04-20 10:54:242579browse

In this article, we will learn what TypeScript is and how to use TypeScript in projects. Recommended: "js tutorial"

Getting Started with TypeScript

What is TypeScript?

● typescript is a superset of JavaScript that can be compiled into pure JavaScript.

● TypeScript is developed and maintained by Microsoft.

● TypeScript provides static type checking for JavaScript code.

● TypeScript provides user-friendly errors at compile time.

Getting Started:

We can use new JavaScript features and future suggestions in TypeScript.

Let’s install the typescript compiler using the node package manager (npm).

Run the following command to install the typescript compiler on your computer.

npm i -g typescript

If you are using mac then you need to add sudo before the command

Run the following command to create a new directory in your machine.

mkdir learn-typescript
cd learn-typescript

Now, open the learn-typescript folder in your favorite code editor and create a new file called dummy.ts.

.ts is a typescript extension.

Writing our first TypeScript code

Let’s write our first TypeScript code in dummy code. ts file.

dummy.ts
let dummy: string = "Hello Boss";

In the above code, we have added a type annotation string so that the dummy variable allows passing string only when we are trying to pass string other than string like number or array.

Compile our TypeScript code

Let us compile the TypeScript code by running the command below.

tsc dummy.ts #tsc : typescript compiler

Now you can see that a new file called dummy.js was generated by the typescript compiler and contains our pure JavaScript code.

Let's generate the first error by passing the wrong value to a dummy variable.

dummy.ts
let dummy: string = "Hello Boss";

dummy = 333

Getting Started with TypeScript

Do you see that the typescript compiler generates an error "333" that cannot be assigned to string?

Enter comments

Type annotations mean that the contract we pass to a variable, function or object will accept a specific type only if we try to pass the wrong type.

TypeScript provides us with different types, most of which come from JavaScript types.

String type

Strings are declared by single quotes (") or double quotes (""). By using string type we quote characters in typescript String data type.

Example:

let welcome:string = "welcome to reactgo.com"

// we can also use template strings in TypeScript

let name: string = `Gowtham`;

Number type

In TypeScript we have floating point numbers just like in JavaScript, these floating point numbers Get type number in TypeScript.

let a: number = 1 ;

Boolean type

Boolean data type has only two values, they are either true or false in typescript, we use boolean The type accepts a Boolean value.

let isActive: boolean = true;

Array

In TypeScript, they are two ways of accepting an array type.

The first method is The element type is followed by array[].

// fruits variable can only accept an array of string types.

let fruits:string[] = ['apples','apricots','avocados'];

In the above code, we added a string type[] with array, so the fruits variable can only accept array with string.

The second way uses the general array type Array

let fruits:Array<string> = [&#39;apples&#39;,&#39;apricots&#39;,&#39;avocados&#39;];

// numbers variable can only accept array of numbers
let numbers:Array<number> = [1,2,3,4,5,6,7,8];

Tuple

In TypeScript, we have tuples, which means we can only Provide a fixed number of element types for the array.

// we declared a tuple
let user:[string,number,string];
// intializing the values
user = [&#39;baby&#39;,33,&#39;programming&#39;]; // TypeScript is happy now

We declare a tuple containing three types: string, number and string, so that we have a fixed length array containing three types.

// we declared a tuple
let user:[string,number,string];
// intializing the values
user = [&#39;baby&#39;,33,&#39;programming&#39;]; // TypeScript is happy now
//re intializing with wrong values
user = [33,'baby',1]; // Error

Output:

Getting Started with TypeScript

any type

Sometimes we are not sure what we can get in this case What types of data TypeScript provides us with an any type.

let isActive:any =  false; // boolean
isActive = "Do your work"; // string

Any type usage in arrays.

let user:any[] = [&#39;1233&#39;,&#39;king&#39;,39,true]

In the above we used the any type because we were not sure we could get What type of data is added to the user array.

function type

Let’s see how to add a type to the function.

// function with two parameters are number type
function add(a:number,b:number):number{
    return a+b;
}

Here, we add a type to the function Parameter and return type numbers have been added.

We can choose to leave the return type to the function, since typescript can automatically determine the return type by looking at the function's return statement.

Let's create a complete Typed function, because in the above code, we just created a function with a type.

let add:(a:number,b:number)=>number;
add = function(a:number,b:number):number{
    return a+b;
 }
add(1,2) //correct

In the above code, we specified exactly the type of the add function.

Optional parameters and default parameters in functions

In typescript, if no parameters are passed typescript will give us an error, and strictly required every parameter will give us an error.

To make function parameters optional, we need to add ? at the end of the parameters.

Optional parameter examples

在上面的代码中,我们精确地指定了add函数的类型。

function welcome(name: string, age?: number): string {
    if (name && age) {
        return `Welcome ${name} and ${age}`
    } else {
        return `Welcome ${name}`
    }
}
welcome(&#39;gowtham&#39;) // ok
welcome(&#39;gowtham&#39;,22) // ok
welcome(&#39;gowtham&#39;,22,&#39;lol&#39;) // error Expected 1-2 arguments, but got 3

在上面的代码中,我们添加了?在age参数的末尾,使其成为可选的。

默认参数的例子

function getLength(arr: number[], length = arr.length) {
    return length
}
getLength([1,2,3,4,5])

void类型

void表示没有返回任何类型,例如,不返回任何类型值的函数。

function alertHello():void{
    alert(&#39;Hello&#39;)
}

alertHello 函数不返回任何值。

never类型

never是函数的返回类型,箭头函数总是抛出异常。

一个永远达不到端点的函数

// throw an exception
function error(err:string):never{
     throw new Error(err);
}
// while loop never stops
function infinteLoop():never{
   while(true){
   }
}

接口

接口有助于我们设计特定的数据形状。

现在让我们创建一个接口。

interface User {
    name: string
    active: boolean
}
let user: User = {
    name: "gowtham",
    active: true
}

在上面的代码中,我们创建了一个具有两个属性的界面用户,其中name属性类型为string, active属性类型为boolean。

现在用户对象应该总是满足接口的形状。

我们还可以使用extends关键字来扩展接口。

interface User {
    name: string
    active: boolean
}
// extending the User interface
interface AdminUser extends User {
    id: string
}
let user: User = {
    name: "gowtham",
    active: true
}
// admin object  should have properties
//present in User interface + AdminUser interface
let admin: AdminUser = {
    name: "john",
    active: true,
    id: "3232hejdjdjf"
}

在这里,我们通过扩展用户界面创建了一个AdminUser界面,因此现在admin对象形状应该是用户界面和AdminUser界面的组合

枚举

枚举是使用enum关键字创建的一组命名常量。在TypeScript中,我们有字符串枚举和数字枚举。

数字枚举

enum Day {
    Monday,
    Tuesday,
    Wednesday
};
console.log(Day.Monday) // 0
console.log(Day.Tuesday) //1
console.log(Day.Wednesday) //2

我们已经创建了一个数值枚举日,默认情况下,第一个枚举数应该用值0初始化,然后自动将下一个枚举数增加1,比如Monday:0,Tuesday:1,Wednesday:2。

字符串枚举

enum Colors{
     Red = "#FF0000",
     Green= "#008000",
     Blue = "#0000FF"
}

在字符串枚举中,我们需要初始化一个常量值,就像上面的代码一样,我们创建了一个Colors带有三个枚举器的枚举。

The above is the detailed content of Getting Started with TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn