Recently, I wrote a vue plug-in with TS. I have harvested some knowledge points and share them with you. There will be more updates in the future.

Gets the type of an attribute on a class

class A{
    n: number
}

const num: A['n'] // number
Copy the code

Capture string type

Note that typeof captures the typeof a string, which is a literal type, not a string

// Capture the type and value of the string
const foo = 'Hello World';

// Use a captured type
let bar: typeof foo;

// bar can only be assigned 'Hello World'
bar = 'Hello World'; // ok
bar = 'anything else'; // Error'
Copy the code

The literal type of the name of the capture key

Typeof is used to get the object type, then keyof is used to remove the key value

const colors = {
  red: 'red',
  blue: 'blue'
};

type Colors = keyof typeof colors;

let color: Colors; / / color is of type 'red' | 'blue'
Copy the code

Specifies the type of this in the constructor

interface A{
    x:number
}
let a:(this:A) = >number
a =function(){
    this.x =123
    this.y = 467// Error, y does not exist
    return 123 
}
Copy the code

typeof

Return data type

const f = (n:number) = >n+1;
type A = typeof f // => (n:number)=>number;
Copy the code

My project: Imperative calls to vue components.

Github.com/any86/vue-c…