TypeScript basic types of study notes

  • 2020-06-15 07:48:42
  • OfStack

There are seven basic types in TypeScript.

1, boolean


var isDone: boolean = false;

2, number

Represents the number in JavaScript. In JavaScript, both "integer" and "floating point" are stored as double-precision floating point types.


var height: number = 6;

3, string

Represents a string. As with JavaScript 1, you can use 1 pair of double quotes (") or 1 pair of single quotes (') to represent strings.


var name: string = "bob";
name = 'smith';

4, array

There are two methods for array declaration in TypeScript.

Use "[]" to declare:


var list: number[] = [1, 2, 3];

(2) Use array types to declare:


var list: Array<number> = [1, 2, 3];

Both declarations can be used without any difference in effect. However, it is recommended that you use only one of them in your code to maintain code style 1.

5, enum

The enumerated type is a new addition to TypeScript, which is not present in JavaScript.


enum Color {
    Red,
    Green,
    Blue
};
var c: Color = Color.Green;

Like C# 1, if you do not declare the value of item 1, then the value of Red above is 0 and then increases by 1 for each item, so Green is 1 and Blue is 2.


enum Color {
    Red = 1,
    Green,
    Blue
};
var c: Color = Color.Green;

So the value of Red is 1, Green is 2, and Blue is 3.

You can also specify a value for each item.


enum Color {
    Red = 1,
    Green = 2,
    Blue = 4
};
var c: Color = Color.Green;

In addition, enumeration type has a special function. If we have a value, but we do not know whether there is a definition in the enumeration type, we can get it in the following way:


enum Color {
    Red = 1,
    Green,
    Blue
};
var colorName: string = Color[2];
alert(colorName);
colorName = Color[4];
alert(colorName);

Then Green and undefined will be output. Since the value of Green is 2, and no enumeration defines a value of 4, undefined is returned.

6, any

Like the default type of a variable in JavaScript, the reference is dynamic and can be assigned to any type. Such as:


var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

When defined as any, it loses its syntax-aware function, which is equivalent to writing JavaScript 1.

It is worth mentioning that any can be used with arrays:


var height: number = 6;
0

7, void

This type can only be used within a function, and you can specify the return type of a function as void to indicate that the function does not return any value.


function warnUser(): void {
    alert("This is my warning message");
}

This is the end of this article, I hope you enjoy it.


Related articles: