温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

TypeScript函数和类型断言怎么使用

发布时间:2022-06-09 09:25:04 来源:亿速云 阅读:152 作者:zzz 栏目:开发技术

这篇文章主要介绍“TypeScript函数和类型断言怎么使用”,在日常操作中,相信很多人在TypeScript函数和类型断言怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”TypeScript函数和类型断言怎么使用”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

    断言

    非空断言

    非空断言就是确定这个变量不是null或者undefined,就是把null或者undefined从他的类型中排除

    function demo(message:string|undefined|null) {
        const str: string = message
    }
    demo(undefined)

    此时我们没有用非空断言,message的值是undefined和null,所以不能赋值给str,此事运行会报错(Type 'string | null | undefined' is not assignable to type 'string'.Type 'undefined' is not assignable to type 'string'.)

    如果用上非空断言

    let message:string
    function demo(message:string|undefined|null) {
        const str: string = message!
    }
    demo(undefined)

    TypeScript函数和类型断言怎么使用

    此时代码没有问题

    类型断言

    确定此时的变量类型

    尖括号

    我们可以用尖括号

    let message: any = "scc"
    let mesLength:number = (<string>message).length

    TypeScript函数和类型断言怎么使用

    as

    as用来判断变量是不是后面的类型

    let message: any = "scc"
    let mesLength:number = (message as string).length

    确定赋值断言

    这个变量一定会被赋值,就可以使用确定赋值断言

    let message!:string

    变量名后面添加一个!就可以

    类型守卫

    ts类型守卫就是起到一个缩小类型范围作用

    trpeof

    typeof关键字可以使用===判断此时的类型是什么

    function demo(message: string | number | boolean) {
        if (typeof message === "string") {
            message.toUpperCase()
        }
    }

    此时message的类型被缩小成string类型,所以能调用toUpperCase方法

    道理很简单,相信有一定基础的同学很快就会明白

    in

    in用来判断变量是否在类型范围内

    interface Person {
        name: string
        age:number
    }
    interface Dog {
        name: string
        walk:string
    }
    type x = Dog|Person
    function all(emp: x) {
        if ("walk" in emp) {
            console.log(d.walk);
        }
    }

    函数

    可选参数

    参数可以设成可选参数,可选参数最好在必填参数和有默认值的参数后面

    function demo(num:number,str?:string){
    }

    默认值参数

    function demo(num:number,bol:boolean = true,str?:string){ 
    }

    bol就是有默认值的参数,如果传值,那么值为传来的值,不传就是默认值

    函数重载

    函数重载可以让函数根据传值得类型,自动选择应该执行的函数

    function add(a1: number, a2: number):number
    function add(a1: string, a2: string):string
    function add(a1: any, a2: any):any {
            return a1 + a2
    }
    console.log(add(20,30));
    console.log(add("scc","brd"));

    TypeScript函数和类型断言怎么使用

    当我们传入不同的值时,会返回调用不同的函数

    到此,关于“TypeScript函数和类型断言怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI