zoukankan      html  css  js  c++  java
  • typescript 点滴

    1 extend的用法

    const x = extend({ a: 'hello' }, { b: 42 });

     2只有在d.ts,你才可以使用  export as 这样子的语法。而且必须有namespace.

    export const aaa = 132;
    export const bbb = 132;
    export as namespace ccc;
    

    3 至今也不知道 安装了@types/sizzle后。

    export = Sizzle;

    class _BB {}
    // 命名空间声明,用于代码提示
    declare global {
      declare namespace nn {
        let BB: typeof _BB;
      }
    }
    // 命名空间实际定义
    window['nn'] = window.nn || {};
    nn.BB = _BB
    

    5

    typeScript 有两种模块化方式,一种是使用 ES6 的 import/export 及其 TS 对这种语法的微小扩展;另一种方式是使用 TS 特有的 namespace (命名空间)。在分析这两种模块化方式之前,我先推荐使用第一种方式,因为第二种方式涉及到模块引用顺序的问题(可以通过 /// <reference path="..." /> 来解决,但感觉不如 import 爽。
    
    如果使用 namespace 方式的模块化,那么所有东西都是全局的,内部引用直接使用即可,TS 能识别出同一命名空间下 export 的内容;外部引用导入即可;全局使用(比如在页面上的 <script> 内,把命名空间写完整就好(仅仍然只能使用 export 的内容。
    
    如果使用 ES6 模块方式的模块化,目前最好的方式可能就是挂到 window 上了,如果是在 Node 下,就需要挂到 global 上。如果要兼容,就得写点代码来判断全局对象。一般来说,用 TypeScript 写代码,就已经决定了要模块化,除非很少的时候需要在页面的 <script> 中调用脚本中的某些对象,这种情况往 window 上挂就行。如果是要做为库来发布,tsc 是可以编译生成 .d.ts 文件的,如果是引用 js,那就不存在静态类型检查的问题;如果是引用 ts,那就以模块化的方式引用;如果想以全局的方式引用 ts,那就在在全局对象上挂一个入口对象,然后在文档里说明,使用前自己申明这个对象(不需要提供 .d.ts),也就几行代码的事情,也不算麻烦。比如
    declare global {
        interface Window {
            myEntry: EntryClass;
        }
    } 
    declare namespace Aaa{
        interface bbb {
        }
    }
    export {  Aaa }

    第一种方式引入。

    import { Aaa } from './m1.d';
    const aaa: Aaa.bbb;

    第二种方式引入。

    例子

    declare namespace Aaa{
        interface bbb {
        }
    }
    // export {  Aaa } 第二种方式引入这里如果不注释为什么会报错。
    /// <reference path="./m1.d.ts" />
    这个/// 不写好像也能检测到,只是为了表明先后顺序。
    const aaa: Aaa.bbb;

    6  declare 和declare global

    两个的作用是一样的,但是在vue-cli的中用的是declare global而且不能去掉globa.

    7 不使用declare也是可以的呀。也可以在其他模块中使用呀。在简单的typescript环境中。

    可以全局使用,但是在vue-cli中则不可以全局使用。

    8  namespace默认是全局的。

    9 declare

    你可以通过 declare 关键字,来告诉 TypeScript,你正在试图表述一个其他地方已经存在的代码(如:写在 JavaScript、CoffeeScript 或者是像浏览器和 Node.js 运行环境里的代码):
    declare的后边不能使用=后,只能生命其他地方已经有的代码,写=号会报错。
    环境声明就好像你与编译器之间的一个约定,如果这些没有在编译时存在,但是你却使用了它们,则事情将会在没有警告的情况下中断。
    环境声明就好像是一个文档。如果源文件更新了,你应该同步更进。所以,当你使用源文件在运行时的新行为时,如果没有人更新环境声明,编译器将会报错。
    

      

    10 以下两个是等效声明, 第一个使用内联注解,第二个使用接口:

    以下两个是等效声明, 第一个使用内联注解,第二个使用接口:
    
    // Sample A
    declare const myPoint: { x: number; y: number };
    
    // Sample B
    interface Point {
      x: number;
      y: number;
    }
    declare const myPoint: Point;

     11 生命同样的接口

    // Lib a.d.ts
    interface Point {
      x: number,
      y: number
    }
    declare const myPoint: Point
    
    // Lib b.d.ts
    interface Point {
      z: number
    }
    
    // Your code
    let myPoint.z // Allowed!

     12 enum的实现源码

     13 type 的enum

    enum Color {
      Red,
      Green,
      Blue
    }
    
    enum Color {
      DarkRed = 3,
      DarkGreen,
      DarkBlue
    }

    14 生命函数的两种方式,一种是,注解方式,一种接口方式。

    内联类型注解

    // variable annotation 变量注解
    let sampleVariable: { bar: number };
    
    // function parameter annotation 函数注解
    function foo(sampleParameter: { bar: number }) {}
    interface Foo {
      foo: string;
    }
    
    // Return type annotated as `: Foo`
    function foo(sample: Foo): Foo {
      return sample;
    }
    interface ReturnString {
      (): string;
    }
    // 它可以表示一个返回值为 string 的函数:
    
    declare const foo: ReturnString;
    
    const bar = foo(); // bar 被推断为一个字符串。
    为了使指定可调用的类型签名更容易,TypeScript 也允许你使用简单的箭头函数类型注解。例如,在一个以 number 类型为参数,以 string 类型为返回值的函数中,你可以这么写:
    const simple: (foo: number) => string = foo => foo.toString();
    可实例化仅仅是可调用的一种特殊情况,它使用 new 做为前缀。它意味着你需用使用 new 关键字去调用它:
    interface CallMeWithNewToGetString {
    new (): string; } // 使用 declare const Foo: CallMeWithNewToGetString; const bar = new Foo(); // bar 被推断为 string 类型

     15. keyof

    http://www.softwhy.com/article-9151-1.html

    16 字面量类型  使用实例

    // 用于创建字符串列表映射至 `K: V` 的函数
    function strEnum<T extends string>(o: Array<T>): { [K in T]: K } {
      return o.reduce((res, key) => {
        res[key] = key;
        return res;
      }, Object.create(null));
    }
    
    // 创建 K: V
    const Direction = strEnum(['North', 'South', 'East', 'West']);
    
    // 创建一个类型
    type Direction = keyof typeof Direction;
    
    // 简单的使用
    let sample: Direction;
    
    sample = Direction.North; // Okay
    sample = 'North'; // Okay
    sample = 'AnythingElse'; // ERROR!

     17  当输入参数是一个函数的时候,如果用ts约定。

    const iTakeSomethingAndPassItAnErr = (x: (err: Error, data: any) => void) => {
      /* 做一些其他的 */
    };
    iTakeSomethingAndPassItAnErr(() => null); // ok
    iTakeSomethingAndPassItAnErr(err => null); // ok
    iTakeSomethingAndPassItAnErr((err, data) => null); // ok
    
    // Error: 参数类型 `(err: any, data: any, more: any) => null` 不能赋值给参数类型 `(err: Error, data: any) => void`
    // iTakeSomethingAndPassItAnErr((err, data, more) => null);

     18 使用mixins

    // 所有 mixins 都需要
    type Constructor<T = {}> = new (...args: any[]) => T;
    
    /////////////
    // mixins 例子
    ////////////
    
    // 添加属性的混合例子
    function TimesTamped<TBase extends Constructor>(Base: TBase) {
      return class extends Base {
        timestamp = Date.now();
      };
    }
    
    // 添加属性和方法的混合例子
    function Activatable<TBase extends Constructor>(Base: TBase) {
      return class extends Base {
        isActivated = false;
    
        activate() {
          this.isActivated = true;
        }
    
        deactivate() {
          this.isActivated = false;
        }
      };
    }
    
    ///////////
    // 组合类
    ///////////
    
    // 简答的类
    class User {
      name = '';
    }
    
    // 添加 TimesTamped 的 User
    const TimestampedUser = TimesTamped(User);
    
    // Tina TimesTamped 和 Activatable 的类
    const TimestampedActivatableUser = TimesTamped(Activatable(User));
    
    //////////
    // 使用组合类
    //////////
    
    const timestampedUserExample = new TimestampedUser();
    console.log(timestampedUserExample.timestamp);
    
    const timestampedActivatableUserExample = new TimestampedActivatableUser();
    console.log(timestampedActivatableUserExample.timestamp);
    console.log(timestampedActivatableUserExample.isActivated);

    19 typescript中局部变量变为全局变量的方法。

    const { called } = new class {
      count = 0;
      called = () => {
        this.count++;
        console.log(`Called : ${this.count}`);
      };
    }();
    
    called(); // Called : 1
    called(); // Called : 2

    20 tslint 对ts语法中不允许带数字,字符串,布尔声明后直接赋值。因为ts已经可以直接判断出类型了。

    Type boolean trivially inferred from a boolean literal, remove type annotation

    21

    interface DataHandleFunctionType {
      (param: []): [];
    };
    type DataHandleFunctionType = (param: []) => [];

     22 enum和接口的区别和联系

    aa: CloudTypeEnum.Huawei = CloudTypeEnum.Huawei;
    CloudTypeInterface.Huawei 接口这个使用只能代表字符串

  • 相关阅读:
    expect 批量自动部署ssh 免密登陆 之 二
    expect 批量自动部署ssh 免密登陆
    Haproxy_haproxy.cfg
    gitlab 权限说明
    Docker限制容器日志大小
    Docker 常用指令
    CentOS下安装Docker
    Vue项目创建build后可修改的配置文件(接口地址配置)
    SpringBoot+Mybatis-plus多数据源配置(MySQL、Sqlserver)
    JQuery序列化表单排除空值的问题
  • 原文地址:https://www.cnblogs.com/coding4/p/11200430.html
Copyright © 2011-2022 走看看