typescript类型系统-学习笔记

659 阅读3分钟

typescript类型系统

基本注解

使用的是:TypeAnnotation的语法,类型声明空间中可用的任何内容都可以用作类型注解。

let num: number;// 数字注解
let str: string:// 字符串注解
let bool: boolean;// 布尔值注解
const boolArray: boolean[];// 数组注解(加上boolean则表示数组中只能存储boolean类型的数据)

interface

把变量合在一起声明

interface Name {
  first: string;
  second: string;
}

let name: Name;
name = {
  first: 'John',
  second: 'Doe'
};
// 强制检查到了漏了一个second,也就是一旦定义了就一定要给到对应的值
name = {
  // Error: 'Second is missing'
  first: 'John'
};

name = {
  // Error: 'Second is the wrong type'
  first: 'John',
  second: 1337
};

内联类型注解

楼下这种的处理方式只是将楼上的interface Name替换为:TypeAnnotation,并且定义的变量直接使用,也是不可定义了之后缺失

let name: {
  first: string;
  second: string;
};

name = {
  first: 'John',
  second: 'Doe'
};

name = {
  // Error: 'Second is missing'
  first: 'John'
};

name = {
  // Error: 'Second is the wrong type'
  first: 'John',
  second: 1337
};

特殊类型

any、 null、 undefined 以及 void。

  • any:所有类型都能被赋值给它,它也能被赋值给其他任何类型。
  • null、 undefined在类型系统中,JavaScript 中的 null 和 undefined 字面量和其他被标注了 any 类型的变量一样,都能被赋值给任意类型的变量
  • :void 来表示一个函数没有一个返回值
function log(message: string): void {
  console.log(message);
}

泛型类型

说说我的理解,泛型肯定是有,然后在这里作用于数组,TypeScript 能推断出 reverse 为 number[] 类型,从而能给你类型安全。于此相似,当你传入一个类型为 string[] 类型的数组时,TypeScrip 能推断 reverse 为 string[] 类型

function reverse<T>(items: T[]): T[] {
  const toreturn = [];
  for (let i = items.length - 1; i >= 0; i--) {
    toreturn.push(items[i]);
  }
  return toreturn;
}

const sample = [1, 2, 3];
const reversed = reverse(sample);

console.log(reversed); // 3, 2, 1

// Safety,因为在来这里不能被赋值了,赋值只能是Number类型的值,其实他是根据了<T>来搞的事情
reversed[0] = '1'; // Error
reversed = ['1', '2']; // Error

reversed[0] = 1; // ok
reversed = [1, 2]; // ok

联合类型

它使用 | 作为标记,如 string | number

function (command: string[] | string) {}

交叉类型

在 JavaScript 中, extend 是一种非常常见的模式,在这种模式中,你可以从两个对象中创建一个新对象,新对象会拥有着两个对象所有的功能。交叉类型可以让你安全的使用此种模式:

function extend<T, U>(first: T, second: U): T & U {
  const result = <T & U>{};
  for (let id in first) {
    (<T>result)[id] = first[id];
  }
  for (let id in second) {
    if (!result.hasOwnProperty(id)) {
      (<U>result)[id] = second[id];
    }
  }

  return result;
}

const x = extend({ a: 'hello' }, { b: 42 });

// 现在 x 拥有了 a 属性与 b 属性
const a = x.a;
const b = x.b;

元组类型

JavaScript 并没有支持类似于元组的支持。开发者通常只能使用数组来表示元组,但是 TypeScript 类型系统支持它。使用 :[typeofmember1, typeofmember2] 能够为元组添加类型注解,元组可以包含任意数量的成员

let nameNumber: [string, number];
// Ok
nameNumber = ['Jenny', 221345];
const [name, num] = nameNumber;
// Error
nameNumber = ['Jenny', '221345'];

类型别名

类型别名其实是先将类型定义好赋值给一个类似定义变量一样定义好的名称

type StrOrNum = string | number;

// 使用
let sample: StrOrNum;
sample = 123;
sample = '123';

// 会检查类型
sample = true; // Error

type Text = string | { text: string };,这里有interface别名定义,也可以这样搞

我正在使用的机场,推荐给你:dukouyun.com/auth/regist…