takeaway

This is a personal TypeScript learning note. The purpose is to read the document closely, review some JavaScript knowledge and leave notes. There will be some translation of important content, and some of my own understanding and supplement will be inserted in the middle. If there is a wrong place welcome to correct.

From the JavaScript to the TypeScript

JS has an unusual relationship with TS, which provides all the functionality of JS with a type checking system on top of it. Of course, TypeScript is a static language compared to a type-checking tool like Flow.

This article is based on the study notes of TS official documents, and some simple translations will be made. (Many subtitle nouns are not intended to be translated, some contents will be written in)

Some basic features of TS

Static type checking

Thanks to the type-checking system, TS can find some TypeErrors before the program runs. This makes it easier to find TypeError and fix it when we write code. Such as:

const message = "hello!";

message();

//This expression is not callable.
//Type 'String' has no call signatures.
Copy the code

TypeError: Message is not a function will be eliminated if executed using ES.

Non-exception error

This is easy to understand, such as some simple spelling mistakes, some basic logic errors, or their own understanding of the ES specification is not enough, TS can check in advance and point out.

//typos
const announcement = "Hello World!";

// How quickly can you spot the typos?
announcement.toLocaleLowercase();
announcement.toLocalLowerCase();

// We probably meant to write this...
announcement.toLocaleLowerCase();
Copy the code
function flipCoin() {
  // Meant to be Math.random()
  return Math.random < 0.5;
//Operator '<' cannot be applied to types '() => number' and 'number'.
}
Copy the code

TypeScript compiler

TSC is the TypeScript compiler. TSC’s role should be split into two parts: type checking and compiling to JS. Babel is not in opposition to TSC. Babel provides @babel/preset-typescript to compile TS files directly, but due to its single-file build nature, Type checking is not possible for code and some language features are not available (but can be written around, const enum, etc.). If you use Babel as a compiler, TSC will need to type check the code using -noemit first.

Several basic TypeScript types

  • string
  • number
  • boolean
  • Arrays
  • Function
  • Object
  • any
  • null and undefined

There is a separate section for types that are not commonly used

Basic writing

Type Annotations on Variables

let myName: string = "Alice";

let myName = "Alice";
// myName can be inferred as 'string'.
Copy the code

Function

function greet(name: string) :string {
  return "Hello, " + name.toUpperCase() + "!!!!!"
}
Copy the code

Anonymous Functions

const names = ["Alice"."Bob"."Eve"];

// Contextual typing for function
names.forEach((s) = > {
  console.log(s.toUppercase());
//Property 'toUppercase' does not exist on type 'string'. Did you mean 'toUpperCase'?
});
Copy the code

Although the variable type is not specified in the anonymous function, TS can infer the type of S from the context.

Object

// The parameter's type annotation is an object type
function printCoord(pt: { x: number; y: number }) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3.y: 7 });



// optionnal properties
function printName(obj: { first: string; last? :string }) {
  //Object is possibly 'undefined'.
  if(obj.last ! = =undefined) {
    // OK
    console.log(obj.last.toUpperCase());
  }
  // A safe alternative using modern JavaScript syntax:
  console.log(obj.last? .toUpperCase()); }Copy the code

Union Types

// narrow the union with code
function printId(id: number | string) {
  if (typeof id === "string") {
    // In this branch, id is of type 'string'
    console.log(id.toUpperCase());
  } else {
    // Here, id is of type 'number'
    console.log(id); }}//Return type is inferred as number[]|string
// number and string both have slice method,
// so we needn't narrow the union
function getFirstThree(x: number[] | string) {
  return x.slice(0.3);
}
Copy the code

Type & Interface

Both Type and interface can define an Object Type. The difference between the two is that interface can add new attributes to an existing interface. If there is no special reason, interface is preferred.

// interface
interface Window {
  title: string
}

interface Window {
  ts: TypeScriptAPI
}

const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});


//type
type Window = {
  title: string
}

type Window = {
  ts: TypeScriptAPI
}

 // Error: Duplicate identifier 'Window'.
Copy the code

Type Assertions

const myCanvas = document.getElementById("main") as HTMLCanvasElement;

const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
Copy the code

Literal Types

function printText(s: string, alignment: "left" | "right" | "center") {
  // ...
}
printText("Hello, world"."left");
printText("G'day, mate"."centre");
//error: Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.


//interface literal
const req = { url: "https://example.com".method: "GET" };
handleRequest(req.url, req.method);
//error:Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'

//correct 1
const req = { url: "https://xxx.com".method: "GET" as "GET" };
handleRequest(req.url, req.method as "GET");

//correct 2
const req = { url: "https://xxx.com".method: "GET" } as const;
handleRequest(req.url, req.method);
Copy the code

null & undefined

StrictNullChecks is set to on. If the value is null or undefined, check strictNullChecks before using it.

function doSomething(x: string | null) {
  if (x === null) {
    // do nothing
  } else {
    console.log("Hello, "+ x.toUpperCase()); }}// TS provides a special operator! Is used to determine whether it is not null or undefined
function liveDangerously(x? :number | null) {
  // No error
  console.log(x! .toFixed()); }Copy the code