1. Introduction

In the last article, we took a look at TypeScript, looked at some of its concepts, features, and differences from javascript, and built a simple development environment for Both NodeJS and browsers. So in this article, we move on to TypeScript’s data types and type manipulation section. Since I have no prior experience in TypeScript development, this will be a series of articles documenting the entire process of learning TypeScript. On the one hand, it is convenient to record the learning process and refer to it at any time. The other aspect is to share it bit by bit to help those who want to learn TypeScript.

For those of you who want to start learning TypeScript from 0, I highly recommend my previous post:

Article 1 – Encounter TypeScript and build a simple TS development environment – Digging for gold

First TypeScript, understanding types and type operations

Chapter 3 – A deeper look at TypeScript functions

In this article, you will learn:

Types unique to TypeScript 3. Differences between unknown types and any types 4. Associative type, tuple type Associative type alias 5. Differences between optional types and associative types 6. , etc.Copy the code

2. The TypeScript type

As you learn TypeScript syntax, you can use my “Encounter TypeScript” ts development environment or the official Playground.

2.1 type string

let name: string = 'hsh';
// ES5: var str1 = 'hsh';
Copy the code

2.2 number type

let num: number = 100;
// ES5: var num = 100;
Copy the code

2.3 a Boolean type

let flag: boolean = true;
// ES5: var flag = true;
Copy the code

2.4 Array type

The Array type can be written in two ways:

The first:

Const names: Array<string> = [] names.push('123') // ES5: var names = []; names.push('123');Copy the code

The second:

// This is recommended const names: number[] = [] types.push(123) // ES5: var names = []; names.push(123);Copy the code

2.5 Null and undefined

let n: null = null; // ES5: var n = null; let u: undefined = undefined; // ES5: var u = undefined;Copy the code

2.6 any type

A special type in TypeScript. Any type can be classified as any. The any type can be assigned by any type:

let info: any = 'Hello world'
info = 123
info = false
Copy the code

TypeScript allows us to do anything on values of type any (call methods, access properties, and so on) without doing any kind of checking beforehand. Such as:

let info: any
info.name // ok
info.get() // ok
info[1] // ok
Copy the code

This doesn’t seem any different from writing javascript code, with few restrictions. But this can be dangerous for developers, because it’s easy to write code that breaks at run time and loses the point of type checking. Unknown types are added to TypeScript3.0 to address the problem of any.

2.7 unknown type

Like any, unknown types can be assigned to any type:

let un: unknown
un = false; // ok
un = '123'; // ok
un = ['123'] // ok
un = 123 // ok
un = {
  name: 'hsh'
} // ok
un = () => {} // ok
un = null // ok
un = undefined // ok
Copy the code

Since the unknown type is intended to solve the problem caused by the any type, the two types must be different. If we try to assign a value of unknown to another type, we can get the following result:

let un: unknown
let value1: string = un // Error
let value2: number = un // Error
let value3: boolean = un // Error
let value4: string[] = un // Error

let value5: any = un // ok
let value6: unknown = un // ok
Copy the code

If the value of unknown is assigned to string, number, or Boolean, an error is reported. If the value is assigned to any or unknown, an error is reported. This means that unknown types can only be assigned to any and to the unknown type itself, which is understandable because unknown types cannot determine what type they are storing. If you can assign to a string, for example, then type detection becomes uncontrollable.

Then let’s see what happens if we do something to a value of type unknown:

let un: unknown
un()  // Error
un[1]  // Error
un.name  // Error
un.get()  // Error
Copy the code

As you can see, after setting the variable UN to type unknown, these operations are no longer considered typed correctly. Therefore, during development, it is better to use unknown type rather than any type when in doubt.

2.8 void type

The void type means that when a function returns no value, it is void.

// ts
function foo(name: string): void {
    console.log(name)
}
foo('hsh')


// ES5
function foo(name) {
    console.log(name);
}
foo('hsh');
Copy the code

Void (undefined); void (undefined); void (undefined);

let value: void
value = undefined // ok
Copy the code

2.9 never type

The never type is the underlying type in TypeScript. The never type is the return type of function expressions or arrow function expressions that always throw an exception or return no value at all:

Function error(message: string): never {throw new error(message); } function infiniteLoop(): never { while (true) {} }Copy the code

The never type can also be annotated:

let value: never // ok
Copy the code

There’s another key application scenario,

function foo(x: string | number): boolean { if (typeof x === 'string') { return true; } else if (typeof x === 'number') { return false; } // If fail is not of type never, this will result in an error: // - Not all conditions return values (in strict mode) // - or check for unreachable code // But since TypeScript understands that the function 'fail' returns type 'never' // it lets you call it, Because you might use it at run time for security or detailed checks. return fail('Unexhaustive'); } function fail(message: string): never { throw new Error(message); }Copy the code

The never and void types differ:

As soon as someone tells you that never means a function that never returns elegantly, you might immediately think of the similar void, whereas void actually means there is no type at all, and never means the type of a value that never exists.

When a function returns a null value, it returns a value of type void, but when a function never returns (or always throws an error), it returns a value of type never. Void can be assigned, but never cannot be assigned to anything other than never itself.

2.10 Tuple type

Tuple types are TypeScript specific. Arrays typically store elements of the same type. If we want to store elements of different types, we use tuples.

let value: [string, number, boolean] = ['hsh', 18, true]   // ok
let value1: [string, number, boolean] = ['hsh', '18', true] // Error
let value2: [string, number, boolean] = ['hsh', 18, 'true']  // Error
Copy the code

When using tuples, you must provide a value for each attribute:

let value: [string, number] = ['hsh'] 
// Error
// Type '[string]' is not assignable to type '[string, number]'.
// Source has 1 element(s) but target requires 2.
Copy the code

Elements in a tuple can be retrieved by index:

Let value: [string, number] = [' HSH ', 123] value[0] // 'HSH' type: string value[1] // 123 type: numberCopy the code

2.11 Parameter types and return value types of functions

Add type annotations to function arguments:

Function sum(num1: number, num2: number): Function printPoint(point: {x: number, y: {x: number, y: {x: number, y: {x: number, y: {x: number, y: {x: number, y: {x: number, y: number}) { console.log(point.x) console.log(point.y) }Copy the code

What is the syntax of the optional type? Look at the following example:

Function printPoint(point: {x: number, y: number, z? X) console.log(point.y) console.log(point.z)} printPoint({x: number}) {console.log(point.y) console.log(point.z) 100, y: 200 }) // ok printPoint({ x: 100, y: 200, z: 300 }) // okCopy the code

2.12 Association Type

A union type is a type composed of two or more other types whose main purpose is to narrow down the scope of types and help developers write more robust code.

function printId(id: String | number | Boolean) {/ / using joint type If need to judge types (typeof id = = = 'string') {id. ToLocaleUpperCase (); } else { console.log(id) } } printId('111') // ok printId(111) // ok printId(false) // okCopy the code

2.13 Type Alias

Type aliases are used to give a type a new name, so that the type can be reused and the code can be reduced.

/ / basic types of type alias type IdType = string | number | Boolean function printIdNew (id: IdType) {console.log(id)} printIdNew('1') // ok printIdNew(1) // OK printIdNew(true) // OK // The type alias of the object type type Type PointType  = { x: number, y: number } function printPointNew(point: PointType) { console.log(point.x) console.log(point.y) } printPointNew({x: 1, y: 2}) // okCopy the code

3. Summary

This article introduces TypeScript types and their operations. It is highly recommended that you type through the examples manually.

This article is the second installment of TypeScript learning from 0. If you are ready to learn TypeScript, follow me and I will keep you updated on this third installment.

Continuously updated…