search.png
关于我
menu.png
浅学TypeScript(5)——type声明类型别名

自定义的类型别名

通过声明类型别名可以提高语义性,同时能减少重复的代码:

interface Animal {
    typ: string;
}
class Duck implements Animal {
    typ: string = "鸭子"
}
class Goose implements Animal {
    typ: string = "鹅"
}
class Fish implements Animal {
    typ: string = "鱼"
}

// 鸭子和鹅可以飞,但是鱼不行
type canFly = (Duck | Goose);

// 必须是可以飞的动物
function fly(animal: canFly): void {
    console.log(animal.typ + '飞走了');
}

let duck = new Duck();
fly(duck);

let goose = new Goose();
fly(goose);

基础类型的类型声明

type t1 = string | number

function f(v: t1) {
    switch (typeof v) {
        case "number":
            console.log("is number");
            break;
        case "string":
            console.log("is string");
            break;
    }
}

// Error:(13, 3) TS2345: Argument of type 'true' is not assignable to parameter of type 't1'.
// f(true);

f("123");
f(123);

ts 会对类型进行检查,确保进入函数的类型复合 t1的类型声明。

静态量的类型声明

type oneOrTwo = 1 | 2 | '1' | '2'

function f(v: oneOrTwo) {
    console.log(v);
}

f(2);
f('1');

// Error:(10, 3) TS2345: Argument of type '3' is not assignable to parameter of type 'oneOrTwo'.
// f(3);

函数的类型声明

type handleString = (string) => void;

function f(handle: handleString, str: string) {
    handle(str)
}

f((s) => console.log(s), "hell world");

通过函数类型声明我们可以对函数的输入和返回类型进行校验,确保进入的是符合我们要求的函数

类型的合并

& 并不是取交集哦,其实是取并集,和 | 一样都是取并集,但是 | 只要满足其中一个,而&表示都需要满足。
这一点好像挺容易混淆。

type t1 = { x: 1 }
type t2 = { y: 1 }
type t3 = t1 & t2

function f3(o: t3) {
    console.log(o);
}

f3({x: 1, y: 1});


type t4 = { x: 1, z: 1}
type t5 = t4 & t3;

function f5(o: t5) {
    console.log(o);
}

f5({x:1, y:1, z: 1});

函数的返回类型约束

ts的箭头函数在声明类型时和es6的lambda是不同的,它代表函数的返回值的类型

// 返回类型约束

type t = () => {
    a: string
    b: number
}

function f4(o: t) {
    console.log(o());
}

f4(function () {
    return {
        a: "123",
        b: 123
    }
})

版权声明

知识共享许可协议 本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。
发布时间:2019年12月05日 15:01:16

评论区#

还没有评论哦,期待您的评论!

关闭特效