Write in the front ~

✏ ️ TypeScript is what

Open the TypeScript Chinese web site, the largest TypeScript font: TypeScript — a superset of JavaScript.



Open theThe official websiteTypeScript isJavaScript with type syntax.TypeScript is a strongly typed programming language built on top of JavaScript that gives you better tools at any scale.

As I understand it, TypeScript is an “upgraded” and “smart” version of JavaScript that allows developers to write JS code more efficiently. I think it’s true that the engine of development and upgrading is “laziness”, and people feel that there are flaws here and there that make it less efficient to use existing stuff, so they make a 2.0 version of TypeScript that’s easier for us to use.

✏️TypeScript development environment

A TypeScript development environment requires two things:

There are two options for installing Node.js. You can install NVM (you are free to use a different node.js version) or install it on the official website. That’s it. That’s it. Get your development environment ready in advance, and you’ll be happy to start TypeScript development

Introduction to TypeScript

✏️ to start my first TypeScript project ~

Create a project

Initialize the first project by typing in the command window

Mkdir first-ts-project && CD first-ts-project // Create a folder named first-ts-project and go to NPM init -v // initialize package.json file NPM install --save-dev typescript // install the latest stable version of typescript NPM install --save-dev typescript@nextCopy the code

Create tsconfig. Json

Method 1:

Method 2: node_modules/.bin/ TSC –init — locale-zh-cn Create tsconfig.json with all compiler parameters and their descriptions

tool

👉 TS Playground provides a tool for compiling TS online at ⭐️ Highlights: Hover over the type name to see its type

👉 Equal

⭐️ Import {Equal}from’@type-challenges/utils’ Import {Equal}from’@type-challenges/utils’ Hover over the type name to check whether the two types are Equal
,y>

✏️TypeScript preparation

TS and JS

TypeScript is a superset of JavaScript. TypeScript provides all JavaScript features. And adds the TypeScript type system on top of it.

Simply put: Whatever JavaScript can do, TypeScript can do, and it can do better and faster.

TS compilation process

‘TS type checking’ and ‘JS generation’ are two separate processes, type checking errors do not affect the generation of JavaScript code!

The type system

In programming languages, there are two types of type systems: 1. Structural class systems: The actual structure of a type determines whether two types are equal or compatible (TypeScript, Haskell, Go,…). 2. Nominal type system: Determine whether two types are equal by their name (C, C++, Java,…)

TS uses the structure type system

Type annotations

Syntax for type annotations in different languages:

Int print(const char*,...) ; Function log(message: string): voidCopy the code

Types and sets

Here is:

Type the alias

In JS Declare variables or constants using let, constructor, and var
In the TS You can use type to declare aliases for types

Type aliases are similar to let variables in that they are block-level scoped, so they cannot have the same name within the same scope. Similarly, the inner type alias hides the outer type of the same name

The types are broadened and narrowed

  1. Type broadening: When a literal is assigned to a let or bar variable, TS does not use the literal type as the type of the variable, but broadens from the literal type to a corresponding broader type. This process is called type broadening.

  2. Type narrowing: In some cases, TS Narrows the type of the variable when it can be more certain.

TS tries to strike a balance between type certainty and flexibility

TS provides a number of methods to help narrow types to improve type determinism: Null Check, as const, Instanceof, Typeof, attribute checking, Tagged Union, user type guarding, and code flow analysis

When declaring a constant with const, TS knows that the constant will not change and will infer the type to the narrowest literal type

Such as:

Take a chestnut type
let a = ‘hello’ string
const a = ‘hello’ “Hello”

⭐️ where a is declared by let and const respectively. A declared by let is inferred from TS to be of relatively broad type. “hello” is a subset of string

Value space and type space

In TS:



Note:

  1. A namespace that contains only type declarations does not generate JS code and does not import variables
  2. The instanceof operator operates only on value Spaces

> The type space contains the types that are unique to TS (type, interface) and those that are common to TS and JS. > the value space contains the types that are unique to JS (const, let, var) and those that are common to TS and JS

⭐️TS escaped to JS code, symbols that do not exist in the value space are erased after escape (similar to Java type erasers)

How do I determine if a symbol is in value space or type space?

Type T = ypeof Person; type T = ypeof Person; Const p:Person) 3. Type predicate — > type space (target as/is HTMLElement) 4. Const,let,var — > value space 5. The symbol after namespace — > value space + type space

There are some operators that exist in both value space and type space, but have completely different meanings, such as: Typeof > in value space, Typeof returns a string representation of JavaScript type (‘string’ ‘number’ ‘bigint’ ‘Boolean’ ‘symbol’ ‘undefined’ ‘object’ ‘function’) > in the type space, Typeof () function returns the TypeScript type of identifier There are the following: [] this $| const extends in

✏️TypeScript basics

The type hierarchy in TS

The Top layer is the complete set Top Type, and the Bottom layer is the empty set Bottom Type

The value of the lower type can be assigned to the change/constant of the upper type. The change/constant of the unknown type can point to any type of value.

any

1. Any is the Top Type and Bottom Type. Variables/constants of type any and other variables/constants can be assigned to each other, but because of this, any is type-insecure, unserviceable, and should be avoided. 2. 3. Any will hide bugs because there is no Type information, and no error will be reported even if it is used incorrectly. For example, if the any type uses a method that does not exist, the system will not report an error. 4. Any hides code design details: the design of the data type is lost

⭐️ How to avoid using any without causing some unnecessary trouble: turn strict mode on in tsconfig or disable implicit any

{"compilerOptions": {"strict": true, "noImplicitAny": true // enable noImplicitAny}Copy the code

unknown

Let a: unknown = 30; //typeof a = unknown 2. The value of unknown can only be compared with that of unknown. Otherwise, an error is reported. An operation or function call can only be performed if the type is narrowed, otherwise an error will be reported

If the type cannot be predicted, do not use any, use unknown and narrow the type before using

Boolean type (Boolean)

Boolean types have only two elements true and false

  1. Let, var variables are broadened to Boolean types, but const constants are literal types
let a = true; //typeof a = boolean
var b = false; //typeof b = boolean
const c = true; //typeof c = true
Copy the code
  1. It is worth noting that the combination of true and false types is pushed back to Boolean

let d: true | false = true; //g will be pushed back to Boolean

The number type

Number: integer, floating point, ±Infinity, NaN(Not a number)

Bigint type

Bigint is a new type that can represent integers of any size. The number range is [-(2^53-1),2^53-1]. Bigint is a literal that follows a number with a lowercase “n”

Bigint cannot be mixed with number and needs to display conversion

String type (string)

    type Dir = 'north'|'south'
    type Direction = Dir | Capitalize<Dir>
    //type Direction = Dir |'North'|'South'
    
Copy the code

String literals are commonly associated with distinguishing data types

Symbol type

Symbol is a new language feature introduced in ES2021

  1. The variables declared by let and var are derived to the symbol type. The unique symbol must be const
  2. Const constants are derived as unique symbols and can also be annotated as unique symbols
import{Equal}from'@type-challenges/utils' let a = Symbol('a'); //typeof a = symbol var a1 = Symbol('a'); //typeof a1 = symbol let a2:unique symbol = a1; //Error const b1:unique symbol = Symbol('b'); //"unique symbol b1" const b1x = Symbol('b'); //"unique symbol b1x" type x = Equal<typeof b1,typeof b1x>; //falseCopy the code

The unique symbol is not a type, but a group of types. Unique symbol B1 and unique symbol b1x are two types

⭐ ️ unique symbol

  1. Unlike other literals, unique symbol types cannot be used directly and must be referenced as “typeof constants”
  2. Assigning a unique symbol to another const will widen the type to symbol. If you do not want to widen the type, you need to annotate it as the corresponding constant typeof

Object Type (Object)

Contrast: JS to define objects and define object types and TS to get object keys and get object type keys

Array type (Array)

2.TS cannot infer an empty array type, only any[] 3. After adding elements to the array, TS can analyze the code and infer the array type

Arrays are annotated in two ways:

  1. T[]

  2. Array interface generic

Tuples (a Tuple)

A Tuple is a subtype of an array. The element type at each index bit of the Tuple is determined

Because tuples are created the same way as arrays, tuples must be annotated

let a: [number] = [1]; let b: [string,string,number] = ['a','b',123]; // If 123 is not number, an error is reported indicating element type mismatchCopy the code

⭐ ️ [… string []] is equivalent to the string [], but [string, the string of… []] inequitable in string [], the former contains at least one element

Enumeration (Enum)

An enumeration is essentially a mapping that produces an object containing that mapping in the value space

  1. Enumerations that do not display assignments automatically increment from 0, enumerations that are assigned integers are displayed (bidirectional mapping exists)
  2. Enumerations showing assignment strings do not have reverse mapping

Enumeration merge: Enumerations can be split into multiple segments and can be merged with namespaces

Constant enumeration

Constant enumerations do not create variables in value space, all references to constant enumerations are replaced with corresponding values (but can be controlled via the preseverConstEnum compiler option) for easy debugging

void,never

⭐️ In TS, void: the function has no explicit return value. Never: The function cannot return

⭐️JS void is a unary operator: it executes the following expression value and returns undefined unconditionally

Write at the end ~

At this point, TypeScript basics notes are complete. After learning TypeScript for the first time and knowing its features and advantages, I think TS is an “intelligent” language. What I see most in class is that TS can identify variable types, so that we can solve the problem that variables cannot be calculated due to different types in JS development. TypeScript has been recommended by more and more people recently, and major Internet companies are adding the language to their recruitment requirements. Therefore, TypeScript will certainly have its unique advantages, and I need to learn and understand the language in a deeper level in the future. If there is any record error, welcome to point out!!