TypeScript学习七:高级类型

91 阅读1分钟

交叉类型

const a1 = <T, U>(arg1: T, arg2: U): T & U => {
  // 使用类型断言判断res为交叉类型 T & U
  let res = {} as T & U;
  res = Object.assign(arg1, arg2);
  return res;
};
a1({ a: 1 }, { b: "abc" });

联合类型

// 联合类型: number | string
const getLen = (content: number | string): number => {
  if (typeof content === "string") {
    return content.length;
  } else {
    return content.toString().length;
  }
};

类型保护

  • is关键字
// 复杂情况下才会使用function,这里只是做个事例
function isString(value: number | string): value is string {
  return typeof value === "string";
}
if (isString(item)) {
  console.log("item is string:", item.length);
} else {
  console.log("item is string:", item.toFixed());
}
  • instanceof
class C9_1 {
  public name1 = "C9_1";
}
class C9_2 {
  public name2 = "C9_2";
}
function getC9() {
  return Math.random() < 0.5 ? new C9_1() : new C9_2();
}
const c9 = getC9();
if (c9 instanceof C9_1) {
  console.log(c9.name1);
} else {
  console.log(c9.name2);
}

type: 类型别名

type Aaa = string;
let str2: Aaa;
str2 = "abc";

字面量类型

type Name = "aaa";
// const name3: Name = "aaa";    // 必须与字面量类型一致为aaa
type Direction = "a1" | "b2" | "c3"; // 由字面量组成的联合类型
function getDirectionFirstLetter(direction: Direction) {
  return direction.substr(0, 1);
}
console.log(getDirectionFirstLetter("b2"));

interface Info1 {
  name: Name;
}
const _info: Info1 = {
  name: "aaa"
};