What you Need to know about TypeScript

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

Young perennial wandering in rivers and lakes, but never put down the hand of the pen, because it knows little, only good learning!

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. For details, see: link to the first article; Usage of type assertion (as) and type narrowing (in\typeof\instanceof) in TS and examples of literal and enumeration types; For details, please see: link to the second article;

Function – dependent constraints, generics, overloading

The article takes about 8 minutes to read.

Function dependent constraint

Function type expression

An 🌰

// Both functions limit the type of s
function greeter(fn: (a: string) = >void) {
     If no string is passed in, no error is reported
    fn("Hello, World");
}
function printToConsole(s: string) {
    console.log(s);
}
greeter(printToConsole);

// Of course, we can use type aliases to name function types:
type GreetFunction = (a: string) = > void;
function greeter(fn: GreetFunction) {
  // ...
}
Copy the code

Call sign

In JavaScript, functions can have attributes in addition to being callable. However, the function-type expression syntax does not allow you to declare attributes. If we want to describe something callable using properties, we can write a call signature using the object type:

An 🌰

type DescribableFunction = {
    description: string;
    (someArg: number) :boolean;
};
function doSomething(fn: DescribableFunction) {
    console.log(fn.description + " returned " + fn(6));
}
Copy the code

Construct the signature

Functions can also be called with the new operator. Refer to these as constructors because they usually create a new object. You can write a construction signature by adding the new keyword before the call signature:

An 🌰

type SomeConstructor = {
    new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
    return new ctor("hello");
}
Copy the code

The generic

Generics: In the simplest sense, generics are generic types. The definition of generics is defined using <> (sharps);

An 🌰

// Define a union type
function join(first: string | number, second: string | number) {
  return `${first}${second}`;
}
join("juejin".".cn");

// There is no problem with this method at the moment, but there is a requirement that second also be passed as a string if first is passed as a string. Similarly, if it's number, it's all number
function join<T> (first: T, second: T) {
  return `${first}${second}`;
}
// Restrict both types to be the same
join<string> ("juejin".".cn");
join<number> (1.2);
Copy the code

You can think of T as a special identifier, and it becomes whatever comes in.

Generic array

There are two ways to define generics if the value you are passing requires a number. The first is to use [] directly, and the second is to use Array< generic >. The form is different. Everything else is the same.

An 🌰

function myFun<T> (params: T[]) {
  return params;
}
myFun<string> ["123"."456"];
function myFun<T> (params: Array<T>) {
  return params;
}
myFun<string> ["123"."456"];
Copy the code

Multiple generic definitions

An 🌰

function join<T.P> (first: T, second: P) {
  return `${first}${second}`;
}
join <number.string> (1."2");
Copy the code

How generics are used

An 🌰

class SelectHero<T> {
  constructor(private hero: T[]) {}
  getHero(index: number): T {
    return this.hero[index]; }}const selectHero = new SelectHero(["Outlaw."."Swift Wind Sword"."Daughter of the Void."]);
console.log(selectHero.getHero(1));
Copy the code

Inheritance in generics

An 🌰

interface Hero {
  name: string;
}
class SelectHero<T extends Girl> {
  constructor(private hero: T[]) {}
  getHero(index: number): T {
    return this.hero[index].name; }}const selectHero = new SelectHero([{name:"Outlaw."}, {name:"Swift Wind Sword"}, {name:"Daughter of the Void."}]);
console.log(selectHero.getHero(1));
Copy the code

Function overloading

Overloading: The function name is the same, but the number or type of arguments is different

Some JavaScript functions can be called with various parameter counts and types. For example, you could write a function to generate a Date that accepts either a timestamp (one argument) or a month/day/year specification (three arguments).

An 🌰

function makeDate(timestamp: number): Date; function makeDate(m: number, d: number, y: number): Date; Function makeDate(mOrTimestamp: number, d? : number, y? : number): Date { if (d ! == undefined && y ! == undefined) { return new Date(y, mOrTimestamp, d); } else { return new Date(mOrTimestamp); } } const d1 = makeDate(12345678); const d2 = makeDate(5, 5, 5); const d3 = makeDate(1, 3); // No overload expects 2 arguments, but overloads do exist that expect either 1 or 3 arguments.Copy the code

conclusion

The way ahead is so long without ending, yet high and low I’ll search with my will unbending. This article focuses on the use of function-related constraints, generics, and overloading. Among them, generics is the key, must have a good grasp! 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!