TypeScrpit学习(小技巧)

Bind 是有害的

bind的返回值是 any,这意味着在函数上调用 bind 会导致你在原始函数调用签名上将会完全失去类型的安全检查。

一个更好的方式的是使用类型注解的箭头函数:

function twoParams(a: number, b: number) {
    
    
  return a + b;
}

let curryOne = (x: number) => twoParams(123, x);
curryOne(456); // ok
curryOne('456'); // Error

如果你想传递一个类成员的函数,使用箭头函数。例如:

class Adder {
    
    
  constructor(public a: string) {
    
    }

  // 此时,这个函数可以安全传递
  add = (b: string): string => {
    
    
    return this.a + b;
  };
}

另一种方法是手动指定要绑定的变量的类型:

const add: typeof adder.add = adder.add.bind(adder);

柯里化

// 一个柯里化函数
let add = (x: number) => (y: number) => x + y;

// 简单使用
add(123)(456);

// 部分应用
let add123 = add(123);

// fully apply the function
add123(456);

创建数组

const foo: string[] = [];

你也可以在创建数组时使用 ES6 的 Array.prototype.fill 方法为数组填充数据:

const foo: string[] = new Array(3).fill('');
console.log(foo); // 会输出 ['','','']

单例模式

传统的单例模式可以用来解决所有代码必须写到 class 中的问题:

class Singleton {
    
    
  private static instance: Singleton;
  private constructor() {
    
    
    // ..
  }

  public static getInstance() {
    
    
    if (!Singleton.instance) {
    
    
      Singleton.instance = new Singleton();
    }

    return Singleton.instance;
  }

  someMethod() {
    
    }
}

let someThing = new Singleton(); // Error: constructor of 'singleton' is private

let instacne = Singleton.getInstance(); // do some thing with the instance

然而,如果你不想延迟初始化,你可以使用 namespace 替代:

namespace Singleton {
    
    
  // .. 其他初始化的代码

  export function someMethod() {
    
    }
}

// 使用
Singleton.someMethod();

对大部分使用者来说,namespace 可以用模块来替代。

// someFile.ts
// ... any one time initialization goes here ...
export function someMethod() {
    
    }

// Usage
import {
    
     someMethod } from './someFile';

构建切换

根据 JavaScript 项目的运行环境进行切换环境变量是很常见的,通过 webpack 可以很轻松地做到这一点,因为它支持基于环境变量的死代码排除。

在你的 package.json script 里,添加不同的编译目标:

"build:test": "webpack -p --config ./src/webpack.config.js",
"build:prod": "webpack -p --define process.env.NODE_ENV='\"production\"' --config ./src/webpack.config.js"

当然,假设你已经安装了 webpack npm install webpack,现在,你可以运行 npm run build:test 了。

使用环境变量也超级简单:


/**
 * This interface makes sure we don't miss adding a property to both `prod` and `test`
 */
interface Config {
    
    
  someItem: string;
}

/**
 * We only export a single thing. The config.
 */
export let config: Config;

/**
 * `process.env.NODE_ENV` definition is driven from webpack
 *
 * The whole `else` block will be removed in the emitted JavaScript
 *  for a production build
 */
if (process.env.NODE_ENV === 'production') {
    
    
  config = {
    
    
    someItem: 'prod'
  };
  console.log('Running in prod');
} else {
    
    
  config = {
    
    
    someItem: 'test'
  };
  console.log('Running in test');
}

Guess you like

Origin blog.csdn.net/shadowfall/article/details/121341945