美文网首页
TypeScript 基础知识

TypeScript 基础知识

作者: sunflower_07 | 来源:发表于2023-08-03 15:45 被阅读0次

    基础类型

    boolean 类型
    const isStatus: boolean = true
    console.log(isStatus)
    
    image.png

    注意:赋值与定义的不一致,会报错;

    number 类型
    const num: number = 123
    
    console.log(num)
    
    string 类型
    const realName1: string = "lin"
    const fullName: string = `A ${realName1}` // 支持模板字符串
    
    console.log(realName1)
    console.log(fullName)
    
    undefined 和 null 类型
    const u: undefined = undefined // undefined 类型
    const n: null = null // null 类型
    
    console.log(u)
    console.log(n)
    
    const age: number = null
    const realName: string = undefined
    
    console.log(age)
    console.log(realName)
    
    image.png
    any 类型

    _ 不清楚用什么类型,可以使用 any 类型。这些值可能来自于动态的内容,比如来自用户输入或第三方代码库_

    let notSure: any = 4
    notSure = "maybe a string" // 可以是 string 类型
    notSure = false // 也可以是 boolean 类型
    
    notSure.name // 可以随便调用属性和方法
    notSure.getName()
    
    

    不建议使用 any,不然就丧失了 TS 的意义。

    数组类型
    const list: number[] = [1, 2, 3]
    list.push(4)
    

    _ 数组里的项写错类型会报错_

    const list2: number[] = [1, 2, "3"]
    
    image.png

    _ push 时类型对不上会报错_

    list2.push("123")
    
    image.png

    如果数组想每一项放入不同数据怎么办?用元组类型

    元组类型

    _ 元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同_

    const tuple: [number, string] = [18, "lin"]
    console.log(tuple)
    

    // 数组里的项写错类型会报错

    const tuple2: [number, string] = ["lili", 20]
    console.log(tuple2)
    
    image.png

    // 越界会报错:

    const tuple3: [number, string] = [18, "lin", true]
    
    image.png
    • 可以对元组使用数组的方法,比如使用 push 时,不会有越界报错_
    const tuple4: [number, string] = [18, "lin"]
    tuple4.push(100)
    

    push 一个没有定义的类型,报错

    const tuple4: [number, string] = [18, "lin"]
    tuple4.push(true)
    
    image.png

    相关文章

      网友评论

          本文标题:TypeScript 基础知识

          本文链接:https://www.haomeiwen.com/subject/skpmpdtx.html