一. enum,何时去使用enum
enum用于映射,以下是基本用法
enum a { todo = 0, // 表示todo等于0,往下依次增加 done, archived, deleted, } let orderstatus = 0; orderstatus = a.todo; orderstatus = a.done; console.log(orderstatus);
通过位运算和enums做权限控制
enum permission { none = 0, // 0000 read = 1 << 0, // 0001 write = 1 << 1, // 0010 delete = 1 << 2, // 0100 manage = read | write | delete, // 二进制的或 // 0111 } type user = { permission: permission; }; const user: user = { permission: 0b0111, }; // 这个值应该是从后台获取 // 用二进制表示权限,若user.permission&permission.write === permission.write 则user.permission有permission.write的所有1 if ((user.permission & permission.write) === permission.write) { console.log('拥有写权限'); }
二. 什么时候用enum会显得很呆
// 以下这种场景就很呆,不如用type+并集 enum fruit { apple = 'apple', banana = 'banana', pineapple = 'pineapple', watermelon = 'watermelon', } let f: fruit = fruit.apple; f = fruit.watermelon; console.log(f);
对比直接用type+并集的方式
// 用type加并集 type fruit = 'apple' | 'banana' | 'watermelon' | 'pineapple'; let f: fruit = 'banana'; f = 'watermelon'; console.log(f);
总结: number + enum 不错,string 和 混用的情况都不太合适,如果没有enum在js中我们可以用map来替代
三. type和interface的区别
什么时候用type?
几乎没有不能用type的场景,它的官方名称应该叫做类型别名(type aliases),也就是给其它类型取一个名字
type name = string; const a: name = 'hi'; type falselike = 0 | '' | null | undefined | false; // 比较特殊的带有属性的函数的声明方式 type fnwithprop = { (a: number, b: number): number; prop: string; }; const f: fnwithprop = (x, y) => { return x + y; }; f.prop = 'hello';
为什么叫做类型别名
type a = string; type b = a; // b 实际上的类型还是string,不是a,也就是说type声明的是一个类型的别名,没有产生新的类型
什么时候用interface
接口interface是面向对象里面的概念,它表示class需要有的一些功能,ts中的功能不仅能描述功能也能描述对象的属性
type a1 = array<string> & { name: string; } & x; interface x { age: number; } // interface就是用面向对象的黑话,把type能做的事情再描述一遍 interface a2 extends array<string>, x { name: string; }
interface描述函数
interface fn { (a: number, b: number): number; xxx: number; } const f: fn = (x, y) => { return x + y; }; f.xxx = 1; console.log(f);
描述日期对象
interface d extends date { } const d: d = new date(); console.log(d);
type和interface的范围
type也能描述对象,是不是就不需要interface? 我感觉并非如此,主要有两点。第一点,其实interface这个特性的出现迎合了面向对象的粉丝的需要,有助于typescript这门语言的推广传播。 第二点之后我会细说。
区别
- interface只描述对象,type则描述所有区别
- type 只是别名interface则是类型声明
四. type和interface的第三个区别
type的重要特性: type不可以重新赋值,这样的好处计算非常快,但是缺点就是type不好扩展
type a = number;
interface可以自动合并,所以可以被扩展
interface x { name: string; } interface x { age: number; } const a: x = { name: 'frank', age: 18, };
interface扩展的例子
// 扩展axios import {axiosrequestconfig} from 'axios' declare module 'axios' { export interface axiosrequestconfig { _autoloading?: boolean; _mock?: string; } } // 扩展string interface string { padzero(length: number): string; } const s = 'hello'; s.padzero(1);
总结
对外api尽量使用interface,方便扩展,对内api尽量用type,防止代码分散
以上就是typescript中的数据类型enum type interface基础用法示例的详细内容,更多关于typescript数据类型enum type interface的资料请关注代码网其它相关文章!
发表评论