Detailed explanation of never, void, unknown types in TS

1. never

never Types are the underlying types in TypeScript. It is used well in the following situations:

  • A function that never returns a value, that is, an infinite loop (for example, if the function contains  while(true) {});
  • A function that always throws an error (such as: function foo() { throw new Error('Not Implemented') }, foo the return type is  never);
 function foo(): never {//永远不会返回结果 // 死循环 while(true) {}
 }

function bar(): never {throw new Error()
 } 

never Can only be assigned to another  never type, so it can be used for comprehensive compile-time checks

Example:

function foo(x: string | number): boolean {if (typeof x === 'string') {return true;} else if (typeof x === 'number') {return false;}// 如果不是一个 never 类型,这会报错:// - 不是所有条件都有返回值 (严格模式下)// - 或者检查到无法访问的代码// 但是由于 TypeScript 理解 `fail` 函数返回为 `never` 类型// 它可以让你调用它,因为你可能会在运行时用它来做安全或者详细的检查。return fail('Unexhaustive');
}

function fail(message: string): never {throw new Error(message);
} 

2. void (null value)

JavaScript does not have the concept of null value (void), in TypeScript, it means没有任何返回值的函数

// 没有返回值的函数,其返回值类型为 void
function alertName(): void { alert('My name is Tom'); } 

Of course you can also declare a variable as void, but you can only assign it a value of  undefined 和 null:

let unusable: void = undefined; 

voidUsage scenarios in functions:

// 如果什么都不写,此时,add 函数的返回值类型为: void
const add = () => { //
}

// 如果return之后什么都不写,此时,add 函数的返回值类型为: void
const add = () => {  return 
}

const add = (): void => {// 此处,返回的 undefined 是 JS 中的一个值return undefined
}
// 这种写法是明确指定函数返回值类型为 void,与上面不指定返回值类型相同
const add = (): void => {// 
} 

3. unknown

unknownIt is a special type in TypeScript, which is used to describe variables of uncertain type. This is any类型similar to , but safer since it is illegal to do anything with unknown values.

function foo() {return 'abc'
}

function bar() {return 123
}

// unknown类型只能赋值给any和unknown类型
// any类型可以赋值给任意类型

let flag = true
let result: unknown // 最好不要使用any
if (flag) {result = foo()
} else {result = bar()
}

let message: string = result //报错
let num: number = result //报错
let num1: unknown = result
let num2: any = result

console.log(result) 

Any operation on an unknown type requires type narrowing or type assertion

Example:

let value: unknown = 123;

console.log(++value )//error:'value' is of type 'unknown'.

console.log(++(value as number) ) 

The union type of unknown with any other type except any is ultimately  unknown a type

Example:

Intersection types composed of unknown and any other type end up being other types

Example:

Of course there are other unkonwfeatures such as:

相等 1. Only OR  operations can be performed on unknown types  不等 , and no other operations can be performed; 2. Values ​​of unknown types cannot access the properties and methods of created instances; 3. When using mapped types, if the unknown type is traversed, nothing will be mapped Properties; you can click www.likecs.com/show-306158… to learn the above.

4. The difference between never and void

1. void Indicates that there is no type, never indicating a type of value that never exists. 2. When a function returns a null value, its return value is voidof type, but when a function never returns (or always throws an error), its return value is neverof type. voidTypes can be assigned to (when strictNullChecking is false), but nevernot to any type other than itself never. 5. Other matters needing attention

unknown, neverare not allowed to execute methods of variables and access internal properties;

neveris a subtype of all types;

at last

We have prepared a front-end information package for everyone. Contains 54, 2.57G front-end related e-books, "Front-end Interview Guide (with answers and analysis)", video tutorials on difficult and key knowledge (full set).



Friends in need can click on the card below to receive it and share it for free

Guess you like

Origin blog.csdn.net/Android_boom/article/details/128682922