十二、 TypeScript 之任意类型 any

首先 any 类型要慎用 数组

首先 any 类型要慎用 函数

js 代码会自行转译类型 致使报错spa

任意类型能够是 Number String Boolean Object ... 等等 JS 中存在的类型code

let a: any;

能够表示 数组中的元素类型blog

let b: any[];

也能够这样图片

let b: Array<any>;

下面能够看一个函数 顺带说一下 throw new Error()字符串

const func = (value) => {
  let type = typeof value;
  if (typeof value === "number") {
    return `your number is ${value}`
  } else if (typeof value === "string") {
    return `your name is ${value}`
  } else if (typeof value === "object") {
    if (value instanceof Array) {
      return `type is Array`
    } else {
      return `type is ${type}`
    }
  } else if (typeof value === "function") {
    return `type is Function`
  }
  throw new Error(`Expected value is Number or String or Array or Function or Object, but got ${type}`)
};

const result = func(true);

console.log(result);

图片描述

能够看出函数的意思 每次找到对应类型都会返回出一段字符串string

若是类型中找不到 则终止 js 运行 而后在终端报错it

相关文章
相关标签/搜索