typescriptメモ(2)


typescriptタイプ
1、関数多参
type addType = (x: number, y: number) => number
let addxy: addType = (ar1, ar2) => ar1 + ar2;

//     
type addType2 = (x: number, y: number, z?: number) => number
let addxyz: addType2;
addxyz = (x, y) => x + y;
addxyz = (x, y, z) => x + y + z;  //           

let addx1 = (x: number, y = 3) => {
    return x + y
}
addx1(1);
addx1(2, 2);

//     
let addx2 = (ar1: number, ...args: number[]) => {}
2、関数の再ロード
function reverse(x: number): number;
function reverse(x: string): string;

//     
function reverse(x: any) { 
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

reverse(1)
reverse('abc')
reverse(true) // error    number string
3、パンチング
  • 問題:
  • const getArray = (value: any, times: number = 5) => {
        return new Array(times).fill(value)
    }
    console.log(getArray(5, 4).map(item => item.length))  //    value any,  lenth  value          ,         
  • 案:
  • const getArray2 = (value: T, times: number = 5): T[] => {
        return new Array(times).fill(value)
    }
    console.log(getArray2('abc', 5).map(item => item.length)) // ok
    console.log(getArray2(12345, 5).map(item => item.length)) // error
    //     value length   
    interface IwithLength {
        length: number
    }
    
    const getArray22 = (value: T, times: number = 5): T[] => {
        return new Array(times).fill(value)
    }
    getArray22(12345, 5);// error
    getArray22('12345', 5);// ok
    //     
    const getArray3 = (x: T, y: U, times = 5): Array => {
        return new Array(times).fill([x, y])
    }
    console.log(getArray3(1, 2))
    console.log(getArray3('a', 2))
    //  keyof  
    const getProps = (obj: T, prop: K) => {
        return obj[prop]
    }
    var myObj = {
        name: 'xing',
        age: 32
    }
    console.log(getProps(myObj, 'name'))
    console.log(getProps(myObj, 'year')) // error
  • 汎型タイプ
  • type F1 = (x: T, y: U, times: number) => Array
    
    let getArray4: (x: T, y: U, times: number) => Array
    
    interface F2 {
        (x: T, y: U, times: number): Array
    }
    
    interface F3 {
        (x: T, y: U, times: number): Array
        array: [T, U]
    }
    
    function xxx(x: T, y: U, times: number): Array {
        return [[x, y]]
    }
    4、クラス
    4.1 prvate static public protected
    テストケース
    /**
     * readonly     
     * static       ,       
     * public         
     * private           (     )
     * protected              (     )
     */
    class Parent {
        public readonly x: number;
        public x1: number;
        private x2: number;
        protected x3: number;
        static x4: number;
    
        constructor() {
            this.x = 1;
            this.x1 = 1;
            this.x2 = 2;
            this.x3 = 2;
            this.x4 = 2;  //error static   this   Parent  ,   parent   
            Parent.x4 = 8; // ok
        }
        public sayP1() { }
        private sayP2() { }
        protected sayP3() { }
        static sayP4() { }
    }
    
    class Son extends Parent {
        z = 1;
        constructor() {
            super();
            console.log(super.x1)
            console.log(super.x2) // error        
            super.sayP2() // error        
            console.log(super.x3)
            super.sayP3()
            console.log(super.x4) //error
        }
    }
    
    const par = new Parent();
    console.log(par.x1)
    console.log(par.x2) // error
    console.log(par.x3) // error
    par.sayP1()
    par.sayP2() // error
    par.sayP3() // error
    
    const son = new Son();
    console.log(son.x1)
    console.log(son.x2) // error
    console.log(son.x3) // error
    son.sayP1()
    son.sayP2() // error
    son.sayP3() // error
    4.2
    class Info {
        name = 'haixing';
        age?: number;
        constructor(x: number, y?: string) {
    
        }
    }
    const info1 = new Info(1);
    console.log(info1.name)
    console.log(info1.age)
    const info2 = new Info(1, 'la');
    4.3 get&set
    class OperString {
        private _name: string = 'haixing'
        get oString() {
            return this._name
        }
        set oString(newValue: string) {
            this._name = newValue;
        }
    }
    
    const o1 = new OperString();
    console.log(o1.oString)
    o1.oString = 'ggg'
    4.4
    abstract class People { //            ,    
        public abstract getPerson(): void; //                    
    }
    
    // const peo = new People(); // error
    class SonPeople extends People {
        getPerson() {
            //        ,                  
        }
    }
    
    const sonp = new SonPeople();
    sonp.getPerson();
    4.4インターフェースとクラス
    //       
    interface Good {
        type: string
    }
    class MyGood implements Good {
        type = 'aaa';
        hehe = 'good'
    }
    5、索引でタイプにアクセスする
    interface IPE {
        age: number
        name: string
    }
    type myAge = IPE['age'] // number
    // type myAge2 = IPE.age; // error
    
    function getProperty(o: T, p: K): T[K] {
        return o[p]
    }
    
    interface Objs {
        [key: string]: T
    }
    let key: keyof Objs  //     string | number
    const objsT: Objs = {
        name: 18
    }
    let keys: Objs['name']  //     number
    6、ES 6のモジュール化
    //    
    export useState
    export useEffect
    export default react
    
    import react ,{useState,useEffect} from 'react'
    7、名前空間
    // space.ts
    namespace Validation {
        const year = 2006;
        export const name = 'lihaixing';
        export const age = 32;
    }
    
    //               
    //    ts => tsx => .d.ts => package.json type  
    
    console.log(Validation.name)
    
    //  import   
    import MyName = Validation.name
    
    //         types
    
    //    
    import React from 'react'
    8、文書の合併を宣言する
    interface AA {
        name: string
        getRes(input: number): number
    }
    interface AA {
        // name:number; // error    
        age: number
        getRes(input: string): string //         
    }
    //      ,      ,   
    let me: AA = {
        name: 'haix',
        age: 12,
        getRes: (input: any): any => {
            if (typeof input === 'string') {
                return 'a'
            } else {
                return 1
            }
        }
    };
    9、グローバル属性とグローバルモジュールを宣言する
  • グローバル属性
  • // d.ts    ,       ,  declare    
    declare function FnForget(): string;
    declare let hulala: string;
    function getTitle() {
        return 'good'
    }
  • グローバルモジュール
  • 文書
    // module-plugin.d.ts
    
    /*~ On this line, import the module which this module adds to */
    import * as m from 'someModule';
    /*~ You can also import other modules if needed */
    import * as other from 'anotherModule';
    declare module 'someModule' {
        /*~ Inside, add new function, classes, or variables. You can use
         *~ unexported types from the original module if needed. */
        export function theNewMethod(x: m.foo): other.bar;
    
        /*~ You can also add new properties to existing interfaces from
         *~ the original module by writing interface augmentations */
        export interface SomeModuleOptions {
            someModuleSetting?: string;
        }
    
        /*~ New types can also be declared and will appear as if they
         *~ are in the original module */
        export interface MyModulePluginOptions {
            size: number;
        }
    }
    //         
    declare module 'react-native'