TypeScript 中 any, never, unknown, null & undefined 和 void 有什么区别

435 阅读2分钟

any

动态类型变量 失去了类型检查作用

any 就是任意类型。写代码时如果不确定属于什么类型,就可以将其定义为 any 类型。

any 类型属于动态类型,它支持和兼容所有的类型。

let anyValue:any;

anyValue = 10;
anyValue = 'kw';
anyValue = true;
anyValue = {};
anyValue();
anyValue.toUpperCase();

never

  • 永远不存在值的类型

    • 抛出异常, 根本没有返回值的函数表达式 或者箭头函数表达式返回值类型

先看一个例子,throwType 函数会抛出一个异常:

function throwType (code: number, message: string) {
    throw {
        code,
        message
    } 
}

throwError(404, 'Not Found')

该函数执行,就会抛出异常,函数不能正常执行完,此时函数的返回值类型就是 never,表示永远没有结果

unknown

unkonwn 类型是未知类型,它是 any 类型对应的安全类型,也就说它不保证类型,但能保证类型安全。

同样还是上面的代码,改为 unkonwn 类型,可以发现编辑器开始报错了:

在使用 unkonwn 类型时,需要对类型加以判断再去使用,从而保证类型的安全:

let anyValue:unknown;

anyValue = 10;
anyValue = 'kw';
anyValue = true;
anyValue = {};
if(typeof anyValue === 'function') {
    anyValue();
}

if(typeof anyValue === 'string') {
    anyValue.toString();
}

任何类型的值都可以赋值给unknown unknown只能赋值给unknown, any

  • null & undefined 默认是所有类型的子类型
    –strictNullChecks 标记null 或者undefined 只能赋值给void 或者他们自己

void

函数没有返回值, 可以定义为void类型void 表示空类型,只用在函数返回值的类型中。当函数没有返回值时,其类型为 void

function log(message:string) {
    console.log(message);
}

log 函数只打印内容,不返回任何内容,所以它的返回值的类型为 void。TS 的类型推断可以正确推断出:

image.png

也可以显式写明返回的类型:

function log(message:string) :void {
    console.log(message);
}

undefined

undefined 是原生 JS 中的一个类型,它的特殊之处就是它既是一个值,又是一个类型:

let a = undefined;
1.

变量 a 的值是 undefined,类型也是 undefined

按照以前学习的函数的知识,函数没有返回值的时候,默认的返回值为 undefined

那么为什么上面的 log 函数的返回值类型为 void 而不是 undefined 呢?

因为 void 表示的意思是空,即物理意义上的不存在,就没这个东西。而 undefined 表示的物理上存在,但存在的这个东西没有内容。所以 log 函数没有显式返回任何内容,也就是符合 void,压根不存在。

function log(message:string) :undefined {
    console.log(message);
    return
}