1.数值常量,替换无心义的switch 中case 0 ,1 。。。bash
enum Direction {
Up = 1,
Down,
Left,
Right
}复制代码
此时,常量Down,是根据Up ,+1,计算获得。ide
数值常量枚举的规则以下:函数
数字字面量引用以前定义的常数枚举成员(能够是在不一样的枚举类型中定义的) 若是这个成员是在同一个枚举类型中定义的,能够使用非限定名来引用。带括号的常数枚举表达式+, -, ~ 一元运算符应用于常数枚举表达式+, -, *, /, %, <<, >>, >>>, &, |, ^ 二元运算符,常数枚举表达式作为其一个操做对象。 若常数枚举表达式求值后为NaN或Infinity,则会在编译阶段报错复制代码
2.字符串常量ui
enum Direction {
LEFT = "left",
RIGHT = "right"
}复制代码
3.返回根据参数类型,返回相同类型,此时用泛型。在函数或者类名、接口名字后添加<T>spa
function identity<T>(arg: T): T {
return arg;
}复制代码
类似的,ts存在泛型接口、泛型类code
interface GenericIdentityFn<T> {
(arg: T): T;
}复制代码
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}复制代码
更高级用法,添加泛型约束:对象
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}复制代码
4.约定一个对象的属性,使用interface.接口
interface Line{ startime:number; endtime:number}复制代码
5.three
1.如何判断为整数ip
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};复制代码
ps:
和全局函数 isNaN() 相比,该方法不会强制将参数转换成数字,只有在参数是真正的数字类型,且值为 NaN 的时候才会返回 true。
Number.isNaN(NaN); // true
Number.isNaN(Number.NaN); // true
Number.isNaN(0 / 0) // true
// 下面这几个若是使用全局的 isNaN() 时,会返回 true。
Number.isNaN("NaN"); // false,字符串 "NaN" 不会被隐式转换成数字 NaN。
Number.isNaN(undefined); // false
Number.isNaN({}); // false
Number.isNaN("blabla"); // false
// 下面的都返回 false
Number.isNaN(true);
Number.isNaN(null);
Number.isNaN(37);
Number.isNaN("37");
Number.isNaN("37.37");
Number.isNaN("");
Number.isNaN(" ");复制代码
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}复制代码
2. ES6 `${one}${two}${three}` 与Number.parseInt(str,2)使用
`${one}${two}${three}` 做为状态位,标识状态
Number.parseInt(str,2),将十进制转为2进制数,某些状况下,与上述能够进行逆操做。
参考文献:
1. JS doc