This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

This series is designed to help you open TypeScript the right way.

preface

TypeScript is a superset of JavaScript… Every time you look at a TypeScript tutorial, the article introduces the benefits of TypeScript over JavaScript from its background, and then throws out a bunch of TypeScript essentials.

But in the end, when I really started to use it, IT seemed that I only learned let Name :string. The knowledge points described in this article can be found in the TypeScript Chinese manual and are more comprehensive.

So instead of casting a wide net, learn how and when TypeScript is used in real life.

A series of more useful TypeScript guides to different TS syntax points for different usage scenarios. Let you not only know TS, but also can use TS🧐.

series

A more practical guide to TypeScript: Getting Started with Ink-Digging (juejin. Cn)

A more practical TypeScript guide: From ES6 classes to TS Decorators (updated)

Ink-free knowledge point introduction

The following sections will be as brief as possible to summarize common concepts and give examples of how to use TypeScript (by default, you have a general understanding of TypeScript).

For further information, each title links to the address of the official website.

The base type

Boolean // Number // number string // string Object // Object number[] String [] Array<number> Array<string> Array< data type > // array any[] Any // Unknown // safe form of any type undefined null // By default null and undefined are subtypes of all types, but if you want to assign them to a variable of a type, To avoid errors, first turn off strict modeCopy the code
Void // Has no type, such as function f:void () {... } No return value never // Type that the function cannot return. Function f(MSG :string):never {throw new Error(MSG)}Copy the code
Enum // Enumeration example: enum Color {Red = 2, Green, Blue} let C: Color = color.green; Log (c) >> 3 console.log(D) >> Red let a:[string,number, Boolean] = [' XXX ',12,true] // tuple Unlike array can exist different types, but the location of the data type and number of one-to-one correspondence type a | b / / joint type, at the same time to accept a variety of types (< string > STR). The length or (STR as string). Length / / type assertion, Asserts that a variable is of a type to prevent errors. // In this case, we assert that STR is of type string, so using the.length method will not fail if we do not know the type of STR in advanceCopy the code

It is important to note that unknown types are not mentioned in many places. Unlike any, unknown can be used to ensure type safety, while any does not perform type checking directly, which is equivalent to JavaScript🤣. Therefore, we can use unknown instead of any in many cases.

Such as:

B = 'ABC' let l:number = (b as string).length We use a type assertion to determine the type. // If we do not use a type assertion, we will get an error. If we use any to determine the type, we will notCopy the code

Learn more about understanding TypeScript any and unknown

Interface (interface)

You can think of an interface as a contract, and the types of contracts that comply must be specified according to the interface.

Basic usage (including common points)

Interface Iperson {readOnly firstName: string // read-only lastName: string sex? : string //? } function showFullName(person: Iperson) {return person. FirstName + person. LastName // person. However, if it has other attributes, it is not required. The redundant parameters will be removed when it is passed in. Object = {firstName:'xx', lastName:'x', qq:'123'} console.log(showFullName(q as Iperson)) Otherwise, the types are inconsistent >> XXCopy the code

Interfaces can also be functional interfaces

Interface SearchFunc {(source: string, subString: string): Boolean; } let mySearch: SearchFunc = function(so: string, su: string) { let result = so.search(su); return result > -1; }Copy the code

Interfaces can also define class types. (For those of you who haven’t used classes, skip to the more useful TypeScript guide: From ES6 classes to TS decorators to give you an idea of how classes can be used.)

Interface Time {currentTime: Date; setTime(d: Date): void; } interface Name { name: string; setname(pname: string): void; } // Class Clock implements Time, Name {Name :string currentTime: Date other: SetTime (d: Date) {this.currentTime = d; } setname(pname: string) { this.name = pname; } constructor(h? : number, m? : number) {} // The constructor class is interface unconstrained}Copy the code

Interfaces can also be inherited:

interface L { len: number; } interface S extends L { area: number; } let s = <S>{}; Let s: s = ({} as s) S. len = 10, s. rea = 100Copy the code

The other uses, we’re going to be in a specific situation and we’re going to be in a situation where it’s going to be confusing if they’re all lined up.

Class (class)

Here you’ll just cover the basics of what a class is, but to get a head start, its application is described in the more useful TypeScript guide: from ES6 classes to TS decorators.

class Animal { private name: string = 'daHuang'; // Private move(distanceInMeters: number = 0) {console.log(' Animal Moved ${distanceInMeters}m. '); }} // extends Dog {bark() {console.log('Woof! Woof! '); } } const dog = new Dog(); dog.bark(); >> Woof! Woof! dog.move(10); >> Animal Moved 10m.dog. name // Error: property 'name' is private and can only be accessed in class 'Animal'.Copy the code

Function (function)

Function declaration

const add = function(x:number = 1,y? :number):number {if(y) return x+y else return x} //add the parameter must be a number and the return value must be a number. X is 1 by default and y is optionalCopy the code

Function overloading

Returns different types depending on the parameters passed in

function add(x:string,y:string):string function add(x:number,y:number):number function add(x,y) { if(typeof(x) === 'string') return 'the string' +x+y else return x+y // add(1,2) Add ('hello','world')// Add (1,'ss')// errorCopy the code

Generics (generic)

Generics are used to create reusable components that can support multiple types of data. This allows users to use components with their own data types.

function fun<T>(x: T,y:number): T { return x; }// Set the type to be like a variable so that it can be used later, depending on the data type, Using the parameters of different fun < string > (" xx ", 12) / / can be fun < string > (123, 12) / / can be fun < number > (' ss '12) / / an errorCopy the code

Type alias type

The type function is to give a new name to a type, supporting primitive types, union types, tuples, and any other handwritten types you need

Example:

type test = number; // Let num: test = 10; Type userOjb = {name:string} // Object type getName = ()=>string // function type data = [number,string] // tuple type numOrFun = Second | getName / / joint typeCopy the code

The whole paper briefly and quickly summarizes the common points of TS, aiming to understand TS in the shortest time, and then learn how to use it.

The following articles will take a look at how TS is used in combination with some mature TS frameworks (such as Vue3-TS and NestJS) or in everyday use. (I always hold the view that if you learn how to use it, see how others use it 🤣)

By the way, if you like this series, might as well pay attention to me, learn together, progress together!