What you Need to know about TypeScript

Write above: This article is the second in a four-part ts series, from getting started to getting into the ground, and it is intended as a study note only.

If you are in full bloom, breeze. If you would acquire more wealth, you must make yourself more valuable.

We left off: TS is a superset of JS; TS has strict type judgment for variables, parameters received by functions and parameters returned. In TS, the difference between type alias and interface is basically the same, but there are still some differences in extension, inheritance, etc. See the first link for details

In this paper, the content

  • Type of protection
    • Type assertion AS
    • Type narrowing in
    • Type narrowing typeof
    • Type narrowing Instanceof can only be used on classes
  • Commonly used type
    • Text type
    • Enumeration type enmu
    • Never type

The article takes about 15 minutes to read.

Type of protection

Sometimes you get type information for a value that typescript doesn’t know about.

// Declare "Waiter" and "Teacher", and pass in an animal(any value) in a judgeWho method (Waiter or Teacher). So we use the joint type, the key symbol is | (vertical)
interface Waiter {
  jiedai: boolean;
  say: () = > {};
}
interface Teacher {
  anjiao: boolean;
  skill: () = > {};
}
function judgeWho(animal: Waiter | Teacher) {
  animal.say(); // This is an error because judgeWho can't determine exactly what instances of the union type are
}
Copy the code

Type assertion – as

A type assertion is an assertion that determines the exact value passed in

// We need to introduce a concept called type protection
Type assertion for type protection: A type assertion is an assertion to determine the exact value that was passed
function judgeWho(animal: Waiter | Teacher) {
  if (animal.anjiao) {
    (animal as Teacher).skill();
  }else{
    (animal asWaiter).say(); }}Copy the code

Like type annotations, type assertions are removed by the compiler and do not affect the runtime behavior of your code.

Type narrowing – in

function judgeWhoTwo(animal: Waiter | Teacher) {
  if ("skill" in animal) {
    animal.skill();
  } else{ animal.say(); }}Copy the code

Type narrowing – typeof

function add(first: string | number, second: string | number) {
  return first + second;
}
function add(first: string | number, second: string | number) {
  if (typeof first === "string" || typeof second === "string") {
    return `${first}${second}`;
  }
  return first + second;
}
Copy the code

Type narrowing – instanceof

// Instanceof type protection can only be applied to classes
class NumberObj {
  count: number;
}
function addObj(first: object | NumberObj, second: object | NumberObj) {
  if (first instanceof NumberObj && second instanceof NumberObj) {
    return first.count + second.count;
  }
  return 0;
}
Copy the code

Commonly used type

Objective: To include the common types in the project, which will be supplemented later.

Text type

Using text types alone is not very valuable (worse).

An 🌰

// x is of type hello, which means that the value must be hello, otherwise an error will be reported
let x: "hello" = "hello";

x = "howdy";
// Type '"howdy"' is not assignable to type '"hello"'.
Copy the code

However, a more useful concept can be expressed by combining words into associations.

An 🌰

function printText(s: string, alignment: "left" | "right" | "center") {
    // ...
}

printText("Hello, world"."left");
printText("G'day, mate"."centre");
// Argument of type '"centre"' is not assignable to parameter of type '"left" | "right" | "center"'.
Copy the code

This limits the parameters as well as the return values.

An 🌰

function compare(a: string, b: string| | 0 1) : - 1{
    return a === b ? 0 : a > b ? 1 : -1;
}
Copy the code

Enumerated type

Enumerations allow developers to define a set of named constants. Using enumerations makes it easier to document intent, or to create a different set of cases.

An 🌰

// Defines an enumeration type of Status
enum Status {
  SUCCESS,
  FAIL,
  WARN,
}
Copy the code

Is there a smart brain thinking, why enum? What’s good about enum?

  • Enumerations make typing easier
  • Easier to record intent

An 🌰

// Beginner programmer writing:
function getStatus(status: number) {
  if (status === 0) {
    return "SUCCESS";
  } else if (status === 1) {
    return "FAIL";
  } else if (status === 2) {
    return "WARN"; }}const result = getStatus(0);
console.log(` status to${result}`);
// Intermediate programmer writing:
const Status = {
  MASSAGE: 0.SPA: 1.DABAOJIAN: 2};function getStatus(status: any) {
  if (status === Status.SUCCESS) {
    return "SUCCESS";
  } else if (status === Status.FAIL) {
    return "FAIL";
  } else if (status === Status.WARN) {
    return "WARN"; }}const result = getStatus(Status.SUCCESS);
console.log(` status to${result}`);
Copy the code

The goal of writing code is not to be a mountain of shit. Next, let’s rewrite it with enumerations.

An 🌰

// Advanced programmer writing:
enum Status {
  SUCCESS,
  FAIL,
  WARN,
}
function getStatus(status: any) {
  if (status === Status.SUCCESS) {
    return "SUCCESS";
  } else if (status === Status.FAIL) {
    return "FAIL";
  } else if (status === Status.WARN) {
    return "WARN"; }}// const result = getServe(Status.SUCCESS);
// console.log(' status is ${result} ');
// Overwrite to enumeration type corresponding value
const result = getServe(1);
// This looks amazing because enumeration types have numeric values, starting from 0 by default. We can see this directly with console.log().
console.log(Status.SUCCESS); / / 0
console.log(Status.FAIL); / / 1
console.log(Status.WARN); / / 2
// Instead of starting at 0 by default, you want to start at 1. We could write it like this.
enum Status {
  SUCCESS = 1,
  FAIL,
  WARN,
}
Copy the code

Never type

The never type is the underlying type in TypeScript. Some examples of how it is naturally allocated:

  • A function that never returns a value (e.gwhile(true) {});
  • A function that always throws an error (e.g.function foo() { throw new Error('Not Implemented') }.fooIs the return type ofnever);

An 🌰

let foo: never; // ok
let foo: never = 123; // Error: Number cannot be assigned to never

// never as the function return type
let bar: never = (() = > {
  throw new Error('Throw my hands in the air like I just dont care'); }) ();Copy the code

In addition to the above methods, it can also be used as a detailed inspection.

An 🌰

function foo(x: string | number) :boolean {
  if (typeof x === 'string') {
    return true;
  } else if (typeof x === 'number') {
    return false;
  }

  // If it 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 because TypeScript understands that the function 'fail' returns type 'never'
  // It lets you call it because you might use it for security or verbose checks at runtime.
  return fail('Unexhaustive');
}

function fail(message: string) :never {
  throw new Error(message);
Copy the code

withvoidThe difference of

When never means a function that never returns elegantly, you might immediately think of void as a similar type, but 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 (when strictNullChecking is false), but never cannot be assigned to anything other than never itself.

conclusion

This article focuses on the use of as, IN, Typeof, and interface in type protection, as well as common types such as literal, enumeration, and never. Please feel free to comment if there is anything wrong. Finally, I recently joined the TS learning group created by the author of Mini-Vue to study together. If you’re interested, get you in the group. There will also be a variety of forms of gambling learning!