浅学TypeScript(5)——type声明类型别名

本文探讨了自定义类型别名在代码中的应用,包括如何提高语义性和减少重复代码,以及类型别名在基础类型、静态量和函数中的声明方式。通过具体示例展示了类型合并和函数返回类型约束的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义的类型别名

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

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
    }
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值