Ts Usage Tips

Variable, attribute

I’m going to empty the variable

// undefined is a subtype of any typelet num: number = undefined;
let num: number = null;
Copy the code

Accessing any property

let anyThing: any = 'hello';
console.log(anyThing.myName);
console.log(anyThing.myName.firstName);
Copy the code

Accessing any method

let anyThing: any = 'Tom';
anyThing.setName('Jerry');
anyThing.setName('Jerry').sayHello();
anyThing.myName.setFirstName('Cat');
Copy the code

Access arbitrary properties and arbitrary methods – no type declaration

let something;
something = 'seven';
something = 7;

something.setName('Tom'); Is equivalent tolet something:any;
something = 'seven';
something = 7;

something.setName('Tom');
Copy the code

Don’t let others change the type – define it yourself

let myFavoriteNumber:string = 'seven';
myFavoriteNumber = 7;

// index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
Copy the code

Don’t let others modify the type – TS deduces the type

let myFavoriteNumber = 'seven';
myFavoriteNumber = 7;

// index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
Copy the code

Qualified variable type – union type

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
Copy the code

object

Object Some attribute is optional

interface Person { name: string; age? : number; }let person:Person = {
    name:'xiao'
}
Copy the code

Object N string properties

And the rest, you know
interface Person {
    [propName: string]: string;
}
Copy the code

The Some property of the object cannot be modified

interface Person {
    readonly id: number;
    name: string;
}
let tom: Person = {
    id: 89757,
    name: 'Tom'}; tom.id = 9527; // index.ts(14,5): error TS2540: Cannot assign to'id' because it is a constant or a read-only property
Copy the code

An array of

Define an array – < type >+[]

let fibonacci: number[] = [1, 1, 2, 3, 5];
Copy the code

Define arrays – generics

let fibonacci: Array<number> = [1, 1, 2, 3, 5];
Copy the code

Define an array-interface

Interface NumberArray {// When the index type is number, the value type must be number [index: number]: number; }let fibonacci: NumberArray = [1, 1, 2, 3, 5];
Copy the code

Define array-type mixed doubles

let tom: [string, number] = ['Tom', 25];

# Assignment section
let tom: [string, number];
tom[0] = 'Tom';

Copy the code

function

Define functions – function declarations

function (x: number, y: number): number {
    return x + y;
};
Copy the code

Define a function – function expression

let mySum = function (x: number, y: number): number {
    return x + y;
};
Copy the code

Define the function-interface

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    returnsource.search(subString) ! = = 1; }Copy the code

Define functions – interface adds attributes

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = <Counter>function (start: number) { };
    counter.interval = 123;
    counter.reset = function() {};return counter;
}

letc = getCounter(); c(10); c.reset(); C.i nterval = 5.0;Copy the code

Define functions – generics

function createArray<T>(length: number, value: T): Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}

createArray<string>(3, 'x'); / / /'x'.'x'.'x']
Copy the code

Define functions – multigenerics

# ts 2.3+, the generic specifies the default type
function swap<T=number, U>(tuple: [T, U]): [U, T] {
    return [tuple[1], tuple[0]];
}

swap([7, 'seven']); / / /'seven'And 7)Copy the code

Define functions – generics + properties, methods

interface Lengthwise {
    length: number;
    count:() => {}
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length);
    return arg;
}
Copy the code

Define functions – generics + interfaces

interface CreateArrayFunc {
    <T>(length: number, value: T): Array<T>;
}

let createArray: CreateArrayFunc;
createArray = function<T>(length: number, value: T): Array<T> {
    let result: T[] = [];
    for (let i = 0; i < length; i++) {
        result[i] = value;
    }
    return result;
}
Copy the code

Function argument – enumeration

enum ETYPE{
    CLICK,
    DBCLICK
}
function handleEvent(ele: Element, event: ETYPE) {
    // do something
}

handleEvent(document.getElementById('hello'), ETYPE.CLICK);  
handleEvent(document.getElementById('hello'), ETYPE.DBCLICK);
Copy the code

Function arguments – enumeration values make more sense

Enum ETYPE{CLICK = 'CLICK', DBCLICK ='double-click'
}
function handleEvent(ele: Element, event: ETYPE) {
    // do something
}

handleEvent(document.getElementById('hello'), ETYPE.CLICK);  
handleEvent(document.getElementById('hello'), ETYPE.DBCLICK);
Copy the code

Function argument – alias

type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
    // do something
}

handleEvent(document.getElementById('hello'), 'scroll'); HandleEvent (document.getelementById (document.getelementById))'world'), 'dbclick'); // Error, event cannot be'dbclick'
Copy the code

Number of function arguments – fixed

   function sum(x: number, y: number): number {
       return x + y;
   }
   sum(1, 2, 3);

   // index.ts(4,1): error TS2346: Supplied parameters do not match any signature of call target
Copy the code

Number of function arguments – not fixed

functionpush(array: any[], ... items: any[]) { items.forEach(function(item) {
       array.push(item);
   });
}
let a = [];
push(a, 1, 2, 3);
Copy the code

Function parameter “type indeterminate” – type judgment

function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split(' ').reverse().join(' '));
    } else if (typeof x === 'string') {
        return x.split(' ').reverse().join(' '); }}Copy the code

Function argument type indeterminate – type assertion

function getLength(something: string | number): number {
    if ((<string>something).length) {
        return (<string>something).length;
    } else {
        returnsomething.toString().length; }}Copy the code

Function parameter “Untyped” – custom union type (alias)

type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
    if (typeof n === 'string') {
        return n;
    } else {
        returnn(); }}Copy the code

Call different implementation methods with the same name

function getString(something: string | number): string {
    return something.toString();
}
Copy the code

Function arguments are optional – optional?

functionbuildName(firstName: string, lastName? : string) {if (lastName) {
        return firstName + ' ' + lastName;
    } else {
        returnfirstName; }}let tomcat = buildName('Tom'.'Cat');
let tom = buildName('Tom');
Copy the code

Function arguments are optional – Default

function buildName(firstName: string, lastName: string = 'Cat') {
    return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom'.'Cat');
let tom = buildName('Tom');
Copy the code

TsBuilt-in types

Boolean, Error, Date, RegExp

let b: Boolean = new Boolean(1);
let e: Error = new Error('Error occurred');
let d: Date = new Date();
let r: RegExp = /[a-z]/;
Copy the code

Document, HTMLElement, Event, NodeList

The types required by the browser environment are preset in TypeScript
let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click'.function(e: MouseEvent) {
  // Do something
});
Copy the code

The nodeJS type is not preset

npm install @types/node --save-dev
Copy the code

class

Class definition – Private attributes

class Animal { private name; private constructor (name) { this.name = name; }}Copy the code

Class definition – Public attributes

class Animal { public name; private constructor (name) { this.name = name; }}Copy the code

Class definition – Read-only property

class Animal {
    readonlyname; public constructor(name) { this.name = name; }}let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';

// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property
Copy the code

Class definition – Abstract methods

abstract class Animal {
    public name;
    public constructor(name) {
        this.name = name;
    }
    public abstract sayHi();
}

Copy the code

Class definition – Inheritance and implementation

interface Alarm {
    alert();
}
interface Light {
    lightOn();
    lightOff();
}
class Door {
}

class SecurityDoor extends Door implements Alarm,Light {
    alert() {
        console.log('SecurityDoor alert');
    }
    lightOn() {
        console.log('Car light on');
    }
    lightOff() {
        console.log('Car light off');
    }
}

class Car implements Alarm {
    alert() {
        console.log('Car alert'); }}Copy the code

Class definition – Generic

class GenericNumber<T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
Copy the code

interface

Interface definition – interface

interface Alarm {
    alert();
}
Copy the code

Interface definition – Inherits the interface

interface Alarm {
    alert();
}

interface LightableAlarm extends Alarm {
    lightOn();
    lightOff();
}
Copy the code

Interface definition – Inheriting classes

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};
Copy the code

Es6 and es7

Class definition – ES6

class Animal {
    constructor(name) {
        this.name = name;
    }
    sayHi() {
        return `My name is ${this.name}`; }}let a = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
Copy the code

Class definition – ES7

class Animal {
    name = 'Jack';

    constructor() {/ /... }}let a = new Animal();
console.log(a.name); // Jack
Copy the code

Class inheritance – ES6 \7

class Cat extends Animal { constructor(name) { super(name); // Call the parent class's constructor(name) console.log(this.name); }sayHi() {
        return 'Meow, '+ super.sayHi(); SayHi ()}}let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
Copy the code

Class static methods – es6\7

class Animal {
    static isAnimal(a) {
        returna instanceof Animal; }}let a = new Animal('Jack');
Animal.isAnimal(a); // true
Copy the code

Class static property – ES7

class Animal {
    static num = 42;

    constructor() {
        // ...
    }
}

console.log(Animal.num); // 42
Copy the code

reference

  • ts

Welcome to our “Long Ahead” for the latest articles