TypeScript$Type-Value-AnyAndMore

86 阅读2分钟

TypeScript$Type-Value-AnyAndMore

TypeScript 定义了一些独特的类型。

1. any

如果不希望检查某个变量的类型——就像普通的 JavaScript 那样,可以将变量声明为 any 类型。

如果不允许隐式的 any 类型——禁止一个变量声明了但是没指定类型(这时默认类型为 any),则可以通过 noImplicitAny 配置项来设置。

2. unknown

any 类似,unknown 也表示任意类型,不同的是 unknown 更安全:可以对 unknown 类型的变量赋值,但是不能进行操作,不可以赋给其他类型的值(除了 anyunknown)。

  • 可以通过 narrow 来解决赋值问题。(narrow 指的是缩小类型的范围)
function f1(a: any) {
  a.b(); // OK
}
function f2(a: unknown) {
  a.b();
// error, 'a' is of type 'unknown'.
}

这在描述函数类型时很有用:

function safeParse(s: string): unknown {
  return JSON.parse(s);
}
 
// Need to be careful with 'obj'!
const obj = safeParse(someRandomString);

3. never

The never type represents values which are never observed.

什么叫未观察的值呢?就是这个值就像不存在一样(你永远都碰不到它)。🤔

function fail(msg: string): never {
  throw new Error(msg);
}
function fn(x: string | number) {
  if (typeof x === "string") {
    // do something
  } else if (typeof x === "number") {
    // do something else
  } else {
    x; // has type 'never'!
  }
}

4. void

void 在 JavaScript 中是保留字,在 TypeScript 中则表示一种类型。

void represents the return value of functions which don’t return a value. It’s the inferred type any time a function doesn’t have any return statements, or doesn’t return any explicit value from those return statements.

void 是针对函数而言的。

Infer:如果函数没有 return 或者 return后没有值,则函数的返回类型为 void

// The inferred return type is void
function noop() {
  return;
}

Annotate:

  • () => void:声明一个函数的返回类型是 void,则这个函数的返回值会被忽略(可以返回任意值)。
    • 并且返回值的类型会赋给接收的变量
type voidFunc = () => void;
 
const f1: voidFunc = () => true;
 
const f2: voidFunc = function () {
  return true;
};
const v1 = f1(); // void
const v2 = f2();
const src = [1, 2, 3];
const dst = [0];
 
src.forEach((el) => dst.push(el));
// Array.prototype.forEach:需要一个返回类型为 void 的函数
// Array.prototype.push:返回值为数字,但是 void 不在乎
  •  字面量函数 literal function definition 的返回值:如果声明为 void,则不允许返回其他值:
function f1(): void {
  // @ts-expect-error
  return true;
}
 
const f2 = function (): void {
  // @ts-expect-error
  return true;
};