Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

TypeScript base type


May 07, 2021 TypeScript



The underlying type

Introduced

In order for the program to be valuable, we need to be able to handle the simplest data units: numbers, strings, structures, Boolean values, etc. TypeScript supports almost the same data types as JavaScript, and also provides useful enumerged types for us to use.

Boolean value

The most basic data type is the simple true/false value, which is called boolean in boolean (as in other languages).

let isDone: boolean = false;

Digital

Like JavaScript, all numbers in TypeScript are floating points. T he type of these floats is number In addition to supporting decal and he heteen literals, Typescript also supports the binary and octal literal quantities introduced in ECMAScript 2015.

let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;

String

Another basic operation of javaScript programs is to work with text data on the Web page or server side. A s in other languages, we use string text data types. Like JavaScript, strings can be represented by " quotes (" or single ' (').

let name: string = "bob";
name = "smith";

You can also use template strings, which define multiple lines of text and embedded expressions. This string is surrounded by inverse ` and is embedded in the expression in the form of ${ expr }

let name: string = `Gene`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ name }.

I'll be ${ age + 1 } years old next month.`;

This works in the same sentence is defined below:

let sentence: string = "Hello, my name is " + name + ".\n\n" +
    "I'll be " + (age + 1) + " years old next month.";

Array

TypeScript manipulates array elements like JavaScript. T here are two ways to define an array. The first, which can be [] followed by an array of elements of this type, can be followed by an array of elements:

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

The second way is to use array generics, Array<元素类型>

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

Tuple for tuples

The group type allows an array that represents the number and type of known elements, each of which does not have to be the same type. For example, you can define a pair of yuan groups string and number values, respectively.

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error

When accessing an element of a known index, you get the correct type:

console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'

When accessing an over-the-border element, the union type is used instead:

x[3] = 'world'; // OK, 字符串可以赋值给(string | number)类型

console.log(x[5].toString()); // OK, 'string' 和 'number' 都有 toString

x[6] = true; // Error, 布尔不是(string | number)类型

The federation type is an advanced topic, which we'll discuss in a later section.

Enumeration

enum type is a complement to the JavaScript standard data type. In other languages, such as C, enumeral types can give a set of values friendly names.

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

By default, the element number starts at 0 Y ou can also manually specify the number of members. For example, let's change the example above 1

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

Alternatively, all are manually assigned:

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

One of the conveniences provided by the enumeration type is that you can get its name from the enumeration worth it. For example, we know the value is 2, but we're not sure which name it maps to in Color, so we can look for the name:

enum Color {Red = 1, Green, Blue};
let colorName: string = Color[2];

alert(colorName);

Any value

Sometimes we want to specify a type for variables that are not clear at the programming stage. T hese values may come from dynamic content, such as user input or third-party code base. I n this case, we don't want the type inspector to examine these values directly through the compilation phase. So we can use any type to mark these variables:

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

The any type is useful when any existing code, allowing you to selectively include or remove type checks at compile time. Y ou might Object has a similar effect, just as it does in other languages. But Object variables just allow you to assign it arbitrary values - but you can't call arbitrary methods on it, even if it does:

let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

Any type is also useful when you know only a portion any data type. For example, you have an array that contains different types of data:

let list: any[] = [1, true, "free"];

list[1] = 100;

The empty value

To some extent, the void appears to be the opposite of any type, which means that there are no types. When a function does not return a value, you usually see that its return value type is void

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

Declaring a void is of little use because you can only give it undefined and null

let unusable: void = undefined;

Null and Undefined

In TypeScript, undefined null each have their own types undefined null Similar void their own types are not very useful:

// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;

By null undefined of all types. That means you can null and undefined variables of number type.

However, when you --strictNullChecks null undefined only be assigned to void void each of them. T his avoids many common problems. M aybe somewhere you want to pass in a string or null or undefined can use string | null | undefined Again, we'll cover the federation type later.

Note: We encourage the use of --strictNullChecks but in this manual we assume that this tag is off.

Never

never type represents the types of values that never exist. For never type is the return value type of a function expression or arrow function expression that always never an exception or does not have a return value at all;

never type is a sub-type of any type and can be assigned never never type; never Even any be assigned to never

Here are some functions that never never:

// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
    throw new Error(message);
}

// 推断的返回值类型为never
function fail() {
    return error("Something failed");
}

// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
    while (true) {
    }
}

Type assertion

Sometimes you'll encounter situations where you'll know more about a value than TypeScript. Usually this happens when you clearly know that an entity has a more accurate type than its existing type.

Type assertion This way you can tell the compiler, "Trust me, I know what I'm doing." T ype assertions are like type transformations in other languages, but do not perform special data checks and deconstruction. I t has no runtime effect, only works during the compilation phase. TypeScript assumes that you, the programmer, have done the necessary checks.

Type assertions come in two forms. One is the "angle bracket" syntax:

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

The other is the as

let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;

The two forms are equivalent. As for which one is used in most cases it is personal preference; however, when you use JSX in TypeScript, only as assertions are allowed.

About let

As you may have noticed, we let keyword instead of the familiar JavaScript keyword var let let keyword is a new concept for JavaScript, and TypeScript implements it. We'll cover it in more detail later, and many common problems can be let so use let instead let var possible.