TS入门-高级类型

108 阅读1分钟

交叉类型

交叉类型是将多个类型合并为一个类型

interface Man{
  name:string
}
interface Job{
  position:string
}
type clerk = Man & Job


const c:clerk = {
  name: 'x',
  position: 'x'
}

联合类型

联合类型表示一个值可以是几种类型之一

type status = string | number
const c:status = 0
const b:status = 'x'
  • 只能访问此联合类型的所有类型里共有的成员
interface A{
  name:string
  count:number
}
interface B{
  name:string
  color:string
}
type C = A | B
const c:C = { name:'xx', count: 10 }
console.log(c.name) // okay
console.log(c.count) // error

类型区分

通过类型区分,确定联合类型的具体类型

  • 属性判断
let pet = getSmallPet();


// 每一个成员访问都会报错
if (pet.swim) {
    pet.swim();
}
else if (pet.fly) {
    pet.fly();
}

*   断言

let pet = getSmallPet();


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

类型保护

类型保护就是一些表达式,它们会在运行时检查以确保在某个作用域里的类型。 既是通过一次类型判断,值在当前作用域下类型为确定值

  • 函数类型保护

返回类型谓词 的断言函数

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}
  • typeof 类型保护
function padLeft(value: string, padding: string | number) {
    if (typeof padding === "number") { // 通过 typeof 明确值类型
        return Array(padding + 1).join(" ") + value;
    }
    if (typeof padding === "string") {
        return padding + value;
    }
    throw new Error(`Expected string or number, got '${padding}'.`);
}
  • instanceof 类型保护
interface Padder {
    getPaddingString(): string
}


class SpaceRepeatingPadder implements Padder {
    constructor(private numSpaces: number) { }
    getPaddingString() {
        return Array(this.numSpaces + 1).join(" ");
    }
}


class StringPadder implements Padder {
    constructor(private value: string) { }
    getPaddingString() {
        return this.value;
    }
}


function getRandomPadder() {
    return Math.random() < 0.5 ?
        new SpaceRepeatingPadder(4) :
        new StringPadder("  ");
}


// 类型为SpaceRepeatingPadder | StringPadder
let padder: Padder = getRandomPadder();


if (padder instanceof SpaceRepeatingPadder) {
    padder; // 类型细化为'SpaceRepeatingPadder'
}
if (padder instanceof StringPadder) {
    padder; // 类型细化为'StringPadder'
}