This is the second day of my participation in the August Text Challenge.More challenges in August

TypeScript type system

TypeScript from 0 (part 1)

The type system is an important concept in TypeScript.

Types can be written implicitly or explicitly in TypeScript


Type implicit and explicit

implicit

In TypeScript, loops try to infer as much type information as possible in order to provide type safety with minimal productivity costs during development.

In the following example, TypeScript knows the variable type and gives an error message. This works in JavaScript, but errors are reported in TypeScript because of the TypeScript type system

var foo = 123;
foo = '456';
Copy the code

Effect:

explicit

TypeScript uses comments to indicate types in type assignments. Benefits:

  • Help the compiler and, more importantly, the next developer who reads the code in the future to record the content
  • Forcing the compiler to see what it should see matches its own understanding of the code with its algorithmic analysis

In TypeScript, postfix type annotations are used, and the developer tells TS what type a variable is (an error is reported if the assigned type is different from the postfix type) :

var foo1: number = 123;
var foo2: number = '123';  // Type '"123"' is not assignable to type 'number' 
var foo3: string = '123';
var foo4: string = 123;  // Type '123' is not assignable to type 'string'.
Copy the code


Type errors do not prevent JavaScript generation

When compiling. Ts files using TSC, TypeScript, by default, issues valid JavaScript files with postfix type comments like these, even if there are compilation errors. The JS file is generated despite the error

Therefore, you can gradually upgrade your JavaScript code to TypeScript. This is quite different from how compilers in many other languages work, and is another reason to migrate to TypeScript.


The type can be environment

A major design goal of TypeScript is to make it safe and easy to use existing JavaScript libraries.

TypeScript implements this through declarations.

For example, a simple jQuery example:

$('.num').show();  // Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.
Copy the code

If you want a quick fix, you can declare in TypeScript that does have a $

The type defined by DECLARE will only be used for compile-time checks and will be removed from the compilation result

declare var $: any
$('.num').show();
Copy the code


TypeScript base types

To make programs valuable, TypeScript supports almost the same data types as JavaScript

TypeScript also exists for all types of data that exist in JavaScript

Boolean value

Boolean in JavaScript and TypeScript, the data type is true/false

let flag: boolean = false;

digital

The number type. In JavaScript and TypeScript, all numbers are floating point.

Also: TypeScript supports imported binary and octal literals. In the number type, you can also assign NaN and Infinity directly

NaN: Most fixed-length integer formats have no way to explicitly represent invalid data Infinity: data of infinite size

TS file:

let num1: number = 10;   / / decimal
let num2: number = 0xf00d;  // Hexadecimal
let num3: number = 0b1010101;  / / binary
let num4: number = 0o744;  / / octal
let num5: number = NaN;
let num6: number = Infinity;
Copy the code

After compilation: Because JavaScript supports hexadecimal, num2 assigned in TS is not converted to decimal data

var num1 = 10; / / decimal
var num2 = 0xf00d; // Hexadecimal
var num3 = 85; / / binary
var num4 = 484; / / octal
var num5 = NaN;
var num6 = Infinity;
Copy the code

string

String. You can use double or single quotation marks to represent strings, or you can use template strings

TS file:

let str1: string = 'hello';
let str2: string = 'world';
let str3: string = `${num1} +

${num2}`;
Copy the code

The compiled:

var str1 = 'hello';
var str2 = 'world';
var str3 = num1 + " +\n\n" + num2;
Copy the code

An array of

In TypeScript, there are two types of annotation that define arrays

  1. Append to the element type[]Data type []
  2. Use array generics —Array< data type >

TypeScript only allows arrays to include values of one data type. If you want to add values of different types to arrays, you need to use associative types

The syntax for creating a union type is as follows:

Type1|Type2|Type3
Copy the code

TS joint types may refer to: www.runoob.com/typescript/…

TS:

let arr1: string[] = ['1'.'2'.'3'];
let arr2: Array<number> = [1.2.3];
let arr3: number[] = [1.'2'];  // Type 'string' is not assignable to type 'number'
let arr4: (number|string)[] = [1.'2'];  // Union type
Copy the code

JS:

var arr1 = ['1'.'2'.'3'];
var arr2 = [1.2.3];
var arr3 = [1.'2']; // Type 'string' is not assignable to type 'number'
var arr4 = [1.'2']; // Union type
Copy the code

In this way, using postfix type annotations seems more cumbersome to write arrays. But it actually works great in large projects.

For example, define an array of individuals with name, age, and score. Name is a string, age is a value, and score is a Boolean value.

TS:

// Define the composition of the Person array
let person: { name: string, age: number, score: boolean }[];
// Add array elements in the defined format
person = [{name: 'kcj'.age: 18.score: true}]
person.push({name: 'anxi'.age: 19.score: false})
Copy the code

This way, if there is a value that does not conform to the specification, it can be easily detected during compilation. Does it look like the class class

Null, and Undefined

Null and undefined can be assigned directly. Generally, undefined is used instead of Null

let jk: string|undefined|null;
jk = null;
jk = undefined;
Copy the code