TypeScript 学习日记(二) Interface 和 对象类型


[!NOTE]
Post Update time: 2024-02-21
Author: J Chow
Refs: 小满TypeScript基础教程全集

  1. interface的设定必须和初始化的对象那的属性一一对应。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    interface AClass{
    name: string
    age: number
    }

    let a: AClass = {
    name: 'J c',
    age:30
    }
  2. 如果定义重名AClass在代码中,编译器将自动合并参数。例如:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    interface AClass{
    name: string
    age: number
    }

    interface AClass{
    sex: string
    }

    let a: AClass = {
    name: 'J c',
    age: 30,
    sex: 'Male'
    }
  3. 如果接受的变量是属于AClass的但是里面还有其他杂七杂八的属性,建议使用索引签名如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    interface AClass{
    name: string
    age: number
    //索引签名
    [propeName: string]: any
    }

    interface AClass{
    sex: string
    }

    let a: AClass = {
    name: 'J c',
    age: 30,
    sex: 'Male'
    }
  4. 如果存在属性非必需,将使用?来申明其可选,示例如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    interface AClass{
    name: string
    age: number
    //索引签名
    [propeName: string]: any
    //可选属性
    company?: string
    }

    interface AClass{
    sex: string
    }

    let a: AClass = {
    name: 'J c',
    age: 30,
    sex: 'Male'
    }
  5. 如果属性不予许强制复制(修改)可以使用修饰符readonly,示例如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    interface AClass{
    name: string
    age: number
    //索引签名
    [propeName: string]: any
    //可选属性
    company?: string,
    //只读修饰符
    readonly callback:()=>boolean
    }

    interface AClass{
    sex: string
    }

    let a: AClass = {
    name: 'J c',
    age: 30,
    sex: 'Male',
    callback:()=>{
    return false
    }
    }

    //以下代码将会报错
    a.callback = ()=>{
    return true
    }
  6. 接口继承使用extends关键词进行继承,然后实力化需要同样有对应的属性。
  7. 使用interface定义函数类型,这样就能够把方法结构定义死,比较安全。
    1
    2
    3
    4
    5
    6
    7
    interface Fn{
    (name: string):number[]
    }

    const fn:Fn = function(name:string){
    return [1,2,3]
    }