走进TypeScript之高级类型

Symbol

symbol生成一个唯一值,symbol类型的值是通过Symbol构造函数创建(es6之后支持)

let sym = Symbol();

symbol值是绝对唯一的,两个同参数的symbol也是不相等的

let sym2 = Symbol("abc");
let sym3 = Symbol("abc");

sym2 === sym3; // false, symbols是唯一的

用作对象属性的键


let sym = Symbol();
let obj = {
  [sym]: "value1",
};

console.log(obj[sym]);

用作类的方法

class TestSymbol {
  [sym4]() {
    console.log("this is a symbao function");
  }
}

let testSymbol = new TestSymbol();
testSymbol[sym4]();

交叉类型

同时拥有定义的多个类型的特性

// 交叉类型
function extend<T, U>(first: T, second: U): T & U {
  let result = <T & U>{};
  for (let id in first) {
    (<any>result)[id] = (<any>first)[id];
  }

  for (let id in second) {
    if (!result.hasOwnProperty(id)) {
      (<any>result)[id] = (<any>second)[id];
    }
  }
  return result;
}

class Person {
  constructor(public name: string) {}
}
interface Loggable {
  log(): void;
}
class ConsoleLogger implements Loggable {
  log() {
    // ...
  }
}
var jim = extend(new Person("Jim"), new ConsoleLogger());
var n = jim.name;
console.log(n);
jim.log();

上边的例子,jim同时拥有Person{}和ConsoleLogger的属性。

联合类型

多个类型之间的关系为“或”,我们用竖线( | )分割每个类型

function padLeft(value: string, padding: string | number) {
    // ...
}

let indentedString = padLeft("Hello world", "Hello world"); 

联合类型类,我们只能访问共有成员

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function getSmallPet(): Fish | Bird {
    // ...
}

let pet = getSmallPet();
pet.layEggs(); // okay
pet.swim();    // errors

类型保护

访问联合类型的类的非共有成员,我们需要使用类型断言来实现类型保护。

let pet = getSmallPet();

if ((<Fish>pet).swim) {
    (<Fish>pet).swim();
}
else {
    (<Bird>pet).fly();
}

typeof

可以使用typeof来实现类型保护,注意:

1. typeof类型保护*只有两种形式能被识别: typeof v === "typename"和 typeof v !== "typename"

2. "typename"必须是 "number", "string", "boolean"或 "symbol"。

function padLeft(value: string, padding: string | number) {
    if (typeof padding === "number") {
        return Array(padding + 1).join(" ") + value;
    }
    if (typeof padding === "string") {
        return padding + value;
    }
    throw new Error(`Expected string or number, got '${padding}'.`);
}

自定义类型保护

1.返回值是一个类型谓词

2. 好处是避免多次断言

function isFish(pet: Fish | Bird): pet is Fish {

    return (<Fish>pet).swim !== undefined;

}

类型别名

type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
  if (typeof n === "string") {
    return n;
  } else {
    return n();
  }
}

字面量类型

// 字符串字面量类型
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
  animate(dx: number, dy: number, easing: Easing) {
    if (easing === "ease-in") {
      // ...
    } else if (easing === "ease-out") {
    } else if (easing === "ease-in-out") {
    } else {
      // error! should not pass null or undefined.
    }
  }
}

let button = new UIElement();
button.animate(0, 0, "ease-in");

// 数值字面量类型
let x = 1 | 2 | 3;

索引类型

1. 使用索引类型,编译器就能够检查使用了动态属性名的代码

2. 通过索引访问操作符(T[K])和索引类型查询操作符(keyof)实现

interface Person {
  name: string;
  age: number;
}

let xiaoming: Person = {
  name: "xiaoming",
  age: 15,
};

function getPersonValue<T extends keyof Person>(key: T): any {
  return xiaoming[key];
}
console.log(getPersonValue("age"));

索引类型和字符串索引签名

interface myMap<T> {
  [key: string]: T;
}

// 说实话,我也不明白哪种场景会用到这种写法,花里胡哨
let keys: keyof myMap<number>; // string
let values: myMap<number>["foo"]; // number
console.log(keys, values);

keyof typeof

enum ColorsEnum {
  white = "#ffffff",
  black = "#000000",
}

type Colors = keyof typeof ColorsEnum;

// 上边的写法相当于 type Colors = "black" | "white";

let myColor: Colors = "black";
console.log(myColor);

映射类型

示例中让已知类型的属性变成可选或者只读

// 示例1
interface myPerson {
  name: string;
  age: number;
}

type readonlyProper<T> = {
  readonly [P in keyof T]: T[P];
};

type partialProper<T> = {
  [P in keyof T]?: T[P];
};

type partialPerson = partialProper<Person>;
type readonlyPerson = readonlyProper<Person>;

let James: partialPerson = { name: "张三" };
let Julia: readonlyPerson = { name: "Julia", age: 12 };

// 示例2
type Keys = "option1" | "option2";
type Flags = { [K in Keys]: boolean };

// 相当于
// type Flags = {
//     option1: boolean;
//     option2: boolean;
// }

其他

// 预定义的有条件类型
// Exclude<T, U> -- 从T中剔除可以赋值给U的类型。
// Extract<T, U> -- 提取T中可以赋值给U的类型。
// NonNullable<T> -- 从T中剔除null和undefined。
// ReturnType<T> -- 获取函数返回值类型。
// InstanceType<T> -- 获取构造函数类型的实例类型。

type T00 = Exclude<"a" | "b" | "c" | "d", "a" | "c" | "f">; // "b" | "d"
type T01 = Extract<"a" | "b" | "c" | "d", "a" | "c" | "f">; // "a" | "c"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值