tricks

作者: JamesSawyer | 来源:发表于2022-11-24 15:20 被阅读0次

type

使用 type 可以声明复杂的数据类型,比如

type Complex = {
  data: number[],
  output: (all: boolean) => number[]
}

let complex: Complex = {
  data: [10, 11],
  output: function(all:boolean) {
    return this.data;
  }
}

never 类型

多用于抛出错误时

function neverReturned(): never {
  throw new Error('some bad thing happens');
}

nullable类型

如果在 tsconfig 中设置

{
  "strictNullChecks": true
  // ...
}

则下面声明会报错

let canBeNull = null;
canBeNull = 12; // 报错

// 可以使用下面几种方式修正这种错误

#1 使用 any 声明
let canBeNull: any = null;
canBeNull = 12; // OK

#2 使用 union 声明
let canBeNull: number | null = null;
canBeNull = 12; // OK

#3 在tsconfig配置中 将 "strictNullChecks" 设置为 false
{
  "strictNullChecks": false
}

let canBeNull = null;
canBeNull = 12; // OK

私有构造器 private constructor && readonly

这个主要用处是,在运行时,只允许有一个实例存在,听起来像单例模式。

class OnlyOneInstance {
    private static instance: OnlyOneInstance;

    private constructor(public readonly name: string) {} // 只读

    static getInstance() {
        if (!OnlyOneInstance.instance) {
            OnlyOneInstance.instance = new OnlyOneInstance('The only one');
        }
        return OnlyOneInstance.instance;
    }
}

如果通过下面方式将报错

let wrong = new OnlyOneInstance()
// 错误
OnlyOneInstance 的构造器是私有的,只能通过class declaration来访问

// 使用下面方式 正确创建实例
let right = OnlyOneInstance.getInstance()

console.log(right.name) // 'The only one'

错误 Accessors are only available when targeting ECMAScript 5 and higher

遇见这个错误可以使用下面命令行

tsc index.ts -t ES5

相关文章

  • Useful tricks for Ubuntu / Ubunt

    Useful tricks Useful tricks in Linux using and server man...

  • tensorflow 试gan记录

    参考tricks: keep calm and train GAN gan tricks 外国友人调DCGAN 为...

  • 学习CSS的资源(暂记)

    1.Google: 关键词 MDN 2.CSS Tricks(https://css-tricks.com) 3....

  • Swift tricks-Phantom Types

    Swift tricks系列收集Swift牛逼的patterns和让你代码更加Swifty的tricks,持续更新...

  • Swift tricks-Nonmutating

    Swift tricks系列收集Swift牛逼的patterns和让你代码更加Swifty的tricks,持续更新...

  • Swift tricks-Enum Associated Va

    Swift tricks系列收集Swift牛逼的patterns和让你代码更加Swifty的tricks,持续更新...

  • tricks

    http://blog.csdn.net/u014365862/article/details/77159778h...

  • tricks

    睫毛膏:在不掉毛的纸巾上蘸,去掉多余液体,不会苍蝇腿;每刷一遍都用✨金属梳齿的睫毛刷疏通✨松润代言的那款 眼妆:先...

  • TRICKS

    C语言linux 向vi复制代码时缩紧会出错,先:set paste然后再Ctrl+Shift+V就可以了 kei...

  • 动画学习

    7、html5tricks: http://www.html5tricks.com/ 网站里有很多前端实现的功能,...

网友评论

      本文标题:tricks

      本文链接:https://www.haomeiwen.com/subject/mlbbdxtx.html