Never数据类型
当我们在tsconfig.json内部打开了"strictNullChecks":true,在这个模式下,ts的undefined和null是能够被检测到的,所以我们需要一种新的数据类型,也就是never
never代表的是永远也不会出现的值。有以下几种使用情况
- 作为不会返回的函数的返回值类型
function error(message:string):nerver{
throw new Error('报错了');
console.log('OK'); // Unreachable code detected.
}
function loop():never{
while(true){
}
console.log('OK') // Unreachable code detected.
}
function fn(x:number|string){
if(typeof x ==='number'){
console.log(x); // 此处可以调用Number类型的方法
}else if(typeof x === 'string'){
console.log(x); // 此处可以调用string类型的方法
}else{
console.log(x); // 这个地方的类型就是never
}
}
void和never的区别
void代表没有任何类型,当一个函数没有返回值的时候,那么他会是一个void类型。如果说一个函数没有返回值,那么他会是一个void类型。如果说一个函数没有返回值,那么他就是一个void类型。
void可以被赋值成null和undefined。never是不能包含任何类型。
当strictNullChecks=false的时候,我们可以将null赋值给void,如果为true的话,就不行了
如果一个函数的返回类型为void函数,能正常执行,但是返回never的函数不能正常执行,或者死循环,或者异常报错。
function greeting():void{
return null;
}
Symbol符号
首先,Symbol是es6才有的数据类型,如果说我们想在typescript中使用Symbol的话,那么我们必须将ESNext的编译选项添加到lib中间来。
{
"compailerOptions": {
"target": "ESNext",
"module": "commonjs",
"strictNullChecks": true,
"lib": ["dom","ESNext"]
}
}
创建了一个Symbol符号就代表创建了一个独一无二的值,他们两个的值肯定是不一样的
const s1 = Symbol('key');
const s2 = Symbol('key');
console.log(s1===s2); //this condition will always return false
BigInt数据类型
BigInt也是es6的数据类型,我们必须在tsconfig.js中使用ESNext才能够使用BigInt数据类型。
const max = Number.MAX_SAFE_INTEGER;
console.log(max+1 === max+2); // 这里已经是最大值了,+1和+2都没意义了,所以这里为true
const max= BigInt(Number.MAX_SAFE_INTEGER);
console.log((max+ BigInt(1)) === max+ BigInt(2)) //false
再就是要注意number和BigInt不兼容的问题,并且要注意Number和BigInt是JS里面的类型,bigint和number是ts里面的类型
let foo:number;
let bar:bigint;
foo=bar;
bar=foo;