TypeScript 学习记录--高级类型

TypeScript 学习记录–高级类型

交叉类型 (& 与的关系)

合并多个类型为一个,拥有每一个类型的所有成员

interface IPerson {
  name: string
}

interface IMen {
  age: number
}

interface IChild {
  parent: IPerson | null
}

type INike = IPerson & IMen & IChild;

const nike: INike =  {
  name: 'nike',
  age: 20,
  parent: null
}

联合类型 (| 或的关系)

type ICount = number | string;

const c: ICount = 90;
const d: ICount = 'www';

可选类型 (?)

function a(count?: number) {
  console.log(a)
}

a(); // run
a(2); // run
a('xx'); // 报错

类型别名

给一个类型起一个名字就是类型别名,根接口 interface 很像,一般用作简单类型的 原始值 | 联合类型 | 元组 等

type Name = string | number

// 类型可以有泛型,亦可以在类型中使用自己
type IA<T> = {
  value: T,
  A: IA<T>
}
  • 与接口 interface 的区别,interface 创建了一个新的名字,可以在其他地方使用,类型并不创建新的名字
  • 类型别名不能被 extends 和 implements
  • 类型别名不能出现在声明的右侧

字面量类型

数字 | 字符串

type IA = 'xxx' | 222

this 类型

class Parent {
  public name: string;
  public render(): this {
    this.name = 'name';
    return this;
  }
  public test(): string {
    return this.name;
  }
}

const p = new Parent();
p.render().test();

索引类型

通过 keyof 将对象的key 作为 类型

interface IObject {
  name: string,
  age: number,
  color: string
}

const obj = {
  name: 'name',
  age: 22,
  color: 'red'
}

const key: keyof IObject = 'name'; // 相当于 'name' | 'age' | 'color'

映射类型

用于将一个已知类型的属性转换类型

interface IObject {
  name: string,
  age: number,
  color: string
}

type IReadOnlyObject = {
  readonly [K in keyof IObject]: boolean
}

const a: IReadOnlyObject = {
  name: false,
  age: true,
  color: false
}

a.name = true; // 报错只读
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值