Coding With Fun
Home Docker Django Node.js Articles FAQ

Reacquaint yourself with | Typescript Vue3 source series


May 31, 2021 Article blog


Table of contents


The following article comes from the public number: Vue Chinese Community, author Knife Brother

Meet for the first time

Officials described it in just one sentence

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. A ny browser. A ny host. A ny OS. Open source.

In general, TypeScript is open source, and TypeScript is a superset of JavaScript types that can be compiled into pure JavaScript. T he compiled JavaScript can run on any browser. The TypeScript compilation tool can run on any server and any system

  • Question: What is a superset

Superset is the term for set theory When it comes to supersets, I have to say another, subset, how to understand these two concepts, for example

If all elements in a set A exist in set B, then we can understand that set A is a subset of collection B, and the opposite set B is a superset of collection A

Now we can understand that TypeScript contains all the features of Javascript, which means that we can run .js suffix directly to .ts file into typeScript's interpretation system

Typescript solves something

The birth of a thing must have its value

So what is the value of TypeScript?

Before we answer this question, it's important to understand TypeScript's work philosophy

Essentially, a static type system (type analysis at compile time) is added to Javascript, emphasizing that the static type system is designed to distinguish it from the type checking mechanism at runtime, and that typeScript's code is eventually compiled as Javascript

Let's go back to the problem itself and narrow it down, and most of the value created by TypeScript is reflected in development (compilation time) rather than runtime, for example

  • Powerful editor intelligence tips (research and development efficiency, development experience)
  • Code readability enhancement (teamwork, development experience)
  • Compile-time type checking (business robust, 70% of Top10 error type low type errors in front-end projects)

body

This article, one of the pre-chapters of Vue3 source series, Typescript Copvin, is intended to show you that you won't be so overwhelmed when faced with Vue3 source code, and will introduce some of Typescript basic uses

Variable statement

The basic type

let isDone: boolean = false
let num: number = 1
let str: string = 'vue3js.cn'
let arr: number[] = [1, 2, 3] 
let arr2: Array<number> = [1, 2, 3] // 泛型数组
let obj: Object = {}
let u: undefined = undefined;
let n: null = null;

Type supplement

  • Enum is enum

Use enumeration types to give a set of values a friendly name

enum LogLevel {
  info = 'info',
  warn = 'warn',
  error = 'error',
}

  • Tuple

Allow arrays to have elements of the same type. For example, you can define a pair of tuples with values of the string and number types, respectively

// Declare a tuple type
let x: [string, number];
// Initialize it
x = ['hello', 10]; // OK
// Initialize it incorrectly
x = [10, 'hello']; // Error

  • Any value Any

Represents any type, often used to determine the type of content, such as from user input or a third-party code base

let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

  • Empty Void

In contrast to any, it is typically used as a function to indicate that no value is returned

function warnUser(): void {
    console.log("This is my warning message");
}

  • Interface interface

Type contract, with our usual adjustment service-side interface to define a field first

The following example point must be consistent with the Point type, and one more is not allowed

interface Point {
    x: number
    y: number
    z?: number
    readonly l: number
}
const point: Point = { x: 10, y: 20, z: 30, l: 40 }
const point2: Point = { x: '10', y: 20, z: 30, l: 40 } // Error 
const point3: Point = { x: 10, y: 20, z: 30 } // Error 
const point4: Point = { x: 10, y: 20, z: 30, l: 40, m: 50 } // Error 

 

Optional and read-only ? Represents optional parameters, readonly represents read-only

const point5: Point = { x: 10, y: 20, l: 40 } // 正常
point5.l = 50 // error

The function argument type and the return value type

function sum(a: number, b: number): number {
    return a + b
}

Use with interface

interface Point {
    x: number
    y: number
}


function sum({ x,  y}: Point): number {
    return x + y
}


sum({x:1, y:2}) // 3

Generics

The meaning of generics lies in the reusability of functions, and the design principle is that components are expected to support not only current data types, but also future data types

  • Like what

According to the original design function of the identity is String as String

function identity(arg: String){
 return arg
}
console.log(identity('100'))

The business iterative process parameters need to support Number

function identity(arg: String){
 return arg
}
console.log(identity(100)) // Argument of type '100' is not assignable to parameter of type 'String'.

Why not use any

Using any loses some information, and we're not sure what type of return value is generic to ensure that the input and return values are of the same type, and that they are special variables that are used only to represent types, not values

Syntax <T>(arg:T):T where T is a custom variable

const hello : string = "Hello vue!"
function say<T>(arg: T): T {
    return arg;
}
console.log(say(hello)) // Hello vue! 

Generic constraints

We used the same example to add a console but we were not lucky enough to report the error because generics could not guarantee that each type had a .length property

const hello : string = "Hello vue!"
function say<T>(arg: T): T {
 console.log(arg.length) // Property 'length' does not exist on type 'T'.
    return arg;
}
console.log(say(hello)) // Hello vue! 

From here we can also see a different place from any if we want to end the fight at the constraint level, we need to define an interface to describe the constraint

interface Lengthwise {
    length: number;
}


function say<T extends Lengthwise>(arg: T): T {
 console.log(arg.length)
    return arg;
}
console.log(say(1))  // Argument of type '1' is not assignable to parameter of type 'Lengthwise'.
console.log(say({value: 'hello vue!', length: 10})) // { value: 'hello vue!', length: 10 } 

The cross type

Intersection Types, which combine multiple types into one type

interface foo {
    x: number
}
interface bar {
    b: number
}
type intersection = foo & bar
const result: intersection = {
    x: 10,
    b: 20
}
const result1: intersection = {
    x: 10
}  // error

The union type

Union Types, which means that a value can be one of several types. W e use vertical | S eparate each type, so number | s tring | Boolean indicates that a value can be number, string, or boolean

type arg = string | number | boolean
const foo = (arg: arg):any =>{ 
    console.log(arg)
}
foo(1)
foo('2')
foo(true)

The function is overloaded

Function Overloading, which allows you to create subroutins with the same name but different input and output types or numbers, can be simply understood as a function's ability to perform multiple tasks

For example, we have an add function that can receive the parameters of string type for stitching, or we can receive parameters of the number type to add up

function add (arg1: string, arg2: string): string
function add (arg1: number, arg2: number): number


// 实现
function add <T,U>(arg1: T, arg2: U) {
  // 在实现上我们要注意严格判断两个参数的类型是否相等,而不能简单的写一个 arg1 + arg2
  if (typeof arg1 === 'string' && typeof arg2 === 'string') {
    return arg1 + arg2
  } else if (typeof arg1 === 'number' && typeof arg2 === 'number') {
    return arg1 + arg2
  }
}


add(1, 2) // 3
add('1','2') //'12'

summary

With this article, I'm sure you won't be unfamiliar with Typescript anymore

Let's take a look at how Typescript in Vue source code is written, and here we take defineComponent function as an example, which you can use to understand and deepen Typescript understanding by combining the content of the article

// overload 1: direct setup function
export function defineComponent<Props, RawBindings = object>(
  setup: (
    props: Readonly<Props>,
    ctx: SetupContext
  ) => RawBindings | RenderFunction
): {
  new (): ComponentPublicInstance<
    Props,
    RawBindings,
    {},
    {},
    {},
    // public props
    VNodeProps & Props
  >
} & FunctionalComponent<Props>


// defineComponent一共有四个重载,这里省略三个


// implementation, close to no-op
export function defineComponent(options: unknown) {
  return isFunction(options) ? { setup: options } : options
}

Here's W3Cschool编程狮 | about reacquainting yourself with Typescript Vue3 source series related to the introduction, I hope to help you.