TypeScript初涉猎

161 阅读3分钟

以下使用ts来作为TypeScript的简称。

什么是ts

js的超集,我理解为强类型的js。js是弱类型的语言,类型在使用中可以随意修改,变更,各种隐式转换,骚操作很多。

因为弱类型的原因,我们的编辑器很难起到很好的提示效果,比如:

function add(num) {
  return num + 1
}

代码运行其实没啥问题,但其实存在隐患,num不一定是Number,可能是一个string?undefiend?null或者其他的,那么运行之后就无法得到预期的结果,可能因为数据类型的原因出现意料之外的bug。

除了bug之外,编辑器也无法起到很好的提示,在使用ts之前,编辑器只能提示我add这个函数需要一个num的参数,但我并不知道会返回我什么类型的值,比如说传入了undefiend,会返回NaN,我拿到NaN去其他地方运行就会报错...为了稳妥起见,我通常会判断返回值的类型来确保add()之后的代码不会出现问题。

有了ts之后,代码是这样的:

function add(num: number): number {
  return num + 1
}

ts会做类型推断,可以判断你传入的参数是否为number,如果不是则会抛出友好的错误提示,add()的返回值也会带上number的类型为后面的代码做推断,保证不会因为类型原因而出现bug。

为什么用ts

  • 提示友好,字段该传什么类型,函数值类型一目了然,多人开发时避免沟通问题,提示类型
  • 原生api提示很足,避免用错api和传错参数类型的开发问题
  • 类型推断,避免因为类型原因而出现的bug,而类型问题通常也是不好排查的
  • 强健的代码通常都会做很多兼容处理和判断,ts的类型推断可以帮我们少写很多代码,减少工作量

安装与配置见官网,webpack加配需要安装ts-loader, 一些简单的类型写法在这里:

const a: string = 'str';
// | 符号代表或者,即可以是number或者string
const b: number | string = 2;
// 也可以具体到某个值,这里可以是string或者是0
const b1: string | 0 = 0;
const c: null = null;
const d: undefined = undefined;
const e: Function = () => 1;
// 也可以跟表达式,只要返回规定类型的值即可
const f: boolean = Boolean(1);
// 类型=数组,数组中每项都只能是number
const g: Array<number> = [1, 2, 3];
// 同上,数组中为string或者number
const g1: Array<string | number> = ['1', 2];
// 如果无法确定类型,或者刚接触ts不会写复杂的类型,使用anyany
const j: any = 123;

// interface一般用来定义比较复杂的类型,可以达到复用、封装、继承的效果

// 定义方法
interface funType {
    (str: string): string
}
// 定义对象
interface objType {
    name?: string
    age: number,
    say: funType
    // 等价于上面写法,say接受一个字符串参数,返回字符串
    // say: (str: string) => string
}
const h: objType = {
    name: '1',
    age: 2,
    say(str: string) { 
        return str
    }
}

// 如果对象中还需要拓展多个类型可以这样
// 意为key=string,value=any
interface objType2 {
    [propName: string]: any
}
const i: objType2 = {
    a: 1
}
i.b = '2';