zoukankan      html  css  js  c++  java
  • typescript高级编程(二)

    类型限制在数组里面写函数

    export interface Plugin {
      extraReducers?: () => {
        [name: string]: (stare: any, ...payload: any) => void
      }
    }
    
    const plugins: Plugin[] = [
      {
        extraReducers() {
          return {
            reducers1(state: any, payload: any) {
            },
          };
        },
      },
      {
        extraReducers() {
          return {
            reducers2(state: any, payload: any) {
            },
          };
        },
      },
    ];
    
    interface ExtraTwo {
      a: () => number
    }
    
    let b: ExtraTwo[] = [
      {
        a() {
          return 1;
        }
      },
      {
        a() {
          return 2;
        }
      }
    ];
    for (let item of b) {
      item.a!();
    }
    我的理解!()是应该是语义化
    
    interface ExtraTwo {
      a: (() => number) | number
    }
    
    let b: ExtraTwo[] = [
      {
        a() {
          return 1;
        }
      },
      {
        a: 0
      }
    ];
    

    as const

    typescript 3.4

    angular7使用的ts3.1

    angular9使用的ts3.7

    不可变断言

    let foo = {
      name: "foo",
      contents: [1,2,3],
    } as const;
    foo.age=12;
    // 报错啦
    interface Icon {
      x: number;
      y: number;
      name: 'we' | 'you' | 'hello' | undefined;
    }
    const myBeautifulIcon: Icon = Object.assign(
      {x: 2, y: 2},
      production ? {name: 'we' } : {name: 'you' as const}
    );
    报错啦,因为name不是确定的值
    修改成
    const myBeautifulIcon: Icon = Object.assign(
      {x: 2, y: 2},
      production ? {name: 'we' as const} : {name: 'you' as const}
    );
    就确定啦
    

    接口

    interface ClockInterface {
      currentTime: Date;
    
      setTime(d: Date): void
    }
    class Clock implements ClockInterface {
      currentTime = new Date();
    
      setTime(d: Date): void {
        this.currentTime = d;
      }
    }
    
    interface Handler<T, P, S> {
      type: T
    
      handle(payload: P): S
    }
    
    class Foos implements Handler<string, object, string> {
      constructor() {
      }
    
      type = 'sss';
    
      handle(payload: object): string {
        this.type = 'bbb';
        return this.type;
      }
    }
    

    Promise 类型限制

    const test = (x: string): Promise<string> => Promise.resolve(x);
    

    Recode 映射的高级用法

    1
    const arr: Record<string, () => void>[] = [
      {
        foo: () => {
        }
      },
      {
        broken: () => {
        }
      }
    ];
    
    2
    type Employee = () => number;
    const add: Employee = () => 1;
    
    3
    type Variations = () => Record<string, () => void>[];
    
    const arrMethod: Variations = () => [
      {
        foo: () => {
        }
      },
      {
        broken: () => {
        }
      }
    ];
    
    type Key = 'a' | 'b' | 'c';
    
    const index1: Record<Key, string> = {a: '', b: 'a', c: 'dd'}; 
    

    递归类型

    type SomeType = { type: 'zero' }
      | { type: 'one', hello: string, next: SomeType };
    
    let mutable: SomeType = {
      type: 'one', hello: 'sss', next: {
        type: 'zero'
      }
    };
    let mutableOne: SomeType = {
      type: 'one', hello: 'aaa', next: {
        type: 'one', hello: 'aaa',
        next: {
          type: 'zero',
        }
      }
    };
    

    遇到的问题

    type SomeType = { type : 'zero' }
                  | { type : 'one', hello : string, next : SomeType };
    
    let mutable : SomeType = { type : 'zero' };
    
    switch( mutable.type ){
        case 'zero' :
            break;
        case 'one' : // error is here, says 'zero' is not comparable to 'one'
            break;
    }
    

    建议这么改

    type SomeType = { type: 'zero' }
      | { type: 'one', hello: string, next: SomeType };
    
    let mutable = {type: 'zero'} as SomeType;
    mutable = {type: 'one', hello: 's', next: {type: 'zero'}} as SomeType;
    switch (mutable.type) {
      case 'zero' :
        break;
      case 'one' : 
        break;
    }
    

    unknown

    typescript3.0

    angular7 ts3.1

    unknown 是 any 类型对应的安全类型

    unknown 和 any 的主要区别是 unknow 类型会更加严格

    let value:any;
    console.log(value.foo.bar);
    
    let value1:unknown;
    console.log(value1.foo.bar);// 报错啦
    

    unknow 类型的主要价值: Typescript不允许我们对类型为unknown的值执行任意操作,相反,我们执行某种类型以缩小值的类型范围

    const value1: any = 'aaa';
    const value2: string = value1;
    
    const value: unknown = "Hello World";
    const someString: string = value;
    // 报错   Type 'unknown' is not assignable to type 'string'.
    修改成
    const value: unknown = "Hello World";
    const someString: string = value as string;
    

    但是也有一个问题

    const value: unknown = 42;
    const someString: string = value as string;
    const otherString = someString.toUpperCase();  // 报错了
    > 这个会在运行时报错
    

    可以把参数当成类型执行判断

    type IsArray<T> = T extends unknown[] ? true : false;
    const arr1: IsArray<string> = false;
    // 可以当成参数参入进去
    const arr2: IsArray<[1, 2, 3]> = true;
    
    interface Dates {
      prop: number
    }
    
    type DatesOne<T> = () => T;
    const add: DatesOne<Dates> = () => ({prop: 1});
    

    关于类型合并的问题

    // a对象 b字符串 c任意
    const add1 = (a, b, c) => {
      return {...a, [b]: c}
    }
    // 添加限制
    const add3 = (a: object, b: string, c: unknown) => {
      return {...a, [b]: c}
    }
    // 问题,我们无法写返回的类型
    //所以需要添加泛型,确认的入口的限制
    function add2<TObject, TName extends string, TValue>(obj: TObject, name: TName, value: TValue) {
      return {...obj, [name]: value}
    }
    // 添加入口的限制
    function add3<TShape, TName extends string, TValue>(
      obj: TShape, name: TName, value: TValue): TShape & { [name in TName]: TValue } {
      return {...obj, [name]: value};// 报错啦
    }
    // 遇到这种情况,可能是typescript还不够完整,暂时解决思路还是强大的断言
    function add3<TShape, TName extends string, TValue>(
      obj: TShape, name: TName, value: TValue) {
      return {...obj, [name]: value} as TShape & { [name in TName]: TValue } ;
    }
    

    提取出完整版

    type TShape<T, N extends string, D> = (obj: T, name: N, value: D) => T & { [name in N]: D };
    const add1: TShape<object, string, unknown> = (a, b, c) => {
      return {...a, [b]: c}
    };
    console.log(add1({name: 'xx'}, 'age', [1, 2, 3]));
    // { name: 'xx', age: [ 1, 2, 3 ] }
    

    源码探索

    lib.es2019.string

    interface String{
        trimEnd():string;
        trimStart():string;
        trimLeft():string;
        trimRight():string;
    }
    

    学习

    interface IntArrays {
      add(): number
    }
    
    const addMethods: IntArrays = {
      add() {
        return 1;
      }
    };
    

    function 在typescript不能被new

    function Foo() {
      return 1;
    }
    
    let a = new Foo();// 报错啦
    

    官网说,这是ECMAscript的工作方式,我不想在代码库中使用,我们可以用class

  • 相关阅读:
    base 镜像
    最小的镜像
    Docker 组件如何协作?- 每天5分钟玩转容器技术(8)
    Docker 架构详解
    容器 What, Why, How
    【视频或者图文】运行第一个容器
    运行第一个容器
    [原]关于helios自定义面板简述
    [osg]osg背景图设置
    [qt]qstring和string中文支持转换问题
  • 原文地址:https://www.cnblogs.com/fangdongdemao/p/13177540.html
Copyright © 2011-2022 走看看