Typescript 别名和字符串字面量类型

类型别名

别名,顾名思义,就是给一个类型起个新名字便于记忆和使用。下面例子让你秒懂并应用。git

// alias.ts
type Name = string;
type ShowName = () => string; // Typescript 中的 =>
type NameOrShowName = Name | ShowName; // 联合类型

const getName = (name: NameOrShowName) => { // ES6 中的 =>
    if(typeof name === 'string'){
        return name;
    } else {
        return name();
    }
}

let showName = () => 'pr is a boy';

console.log(getName('pr')); // pr
console.log(getName(showName())); // pr is a boy
复制代码

注:不要混淆了 TypeScript 中的 => 和 ES6 中的 =>github

在 TypeScript 的类型定义中,=> 用来表示函数的定义,左边是输入类型,须要用括号括起来,右边是输出类型;typescript

在 ES6 中,=> 叫作箭头函数;markdown

固然,Typescript 有能够使用箭头函数,只不过上面是想说明二者的区别;函数

发现:oop

1.建立别名须要使用关键字 typepost

2.使用别名一般用在有联合类型的场景下;ui

字符串字面量类型

它是用来约束只能从定义的字段中取值。spa

// string.ts
type EventNames = 'click' | 'scroll' | 'mousemove';
const handleEvent: (a: Element, b: EventNames) => string = (ele: Element, event: EventNames) => {
    return `${ele} ${event}`;
}

handleEvent(document.getElementById('header'), 'scroll');
handleEvent(document.getElementById('footer'), 'keyup');

// 0.1.1/string.ts:7:48 - error TS2345: Argument of type '"keyup"' is not assignable to parameter of type 'EventNames'.
    // 7 handleEvent(document.getElementById('footer'), 'keyup'); 
复制代码

上面报错是由于 keyup 不在 EventNames 中。code

发现:

定义类型别名与字符串字面量类型用的都是 type

本次代码 Github

你能够...

上一篇:Typescript 类与接口

下一篇:Typescript 泛型

目录:Typescript 小书之入门篇