Ts基础之接口和对象类型

115 阅读1分钟

定义对象的方式要用关键字interface(接口)

像这样写就会报错。

图片.png

此时,如果遇到重名的,他就会合并在一起。但是 a 也要加多一个 gender 属性。

2.png

任意属性 [propName: string]

// 任意属性 [propName: string]

interface Axxsxs{
    gender: string,
    [propName:string]:any // 就不会去检验他,如果定义为 string 类型,就所有类型必须为 string
}

// 添加 c、d 都不会报错
let a:Axxsxs ={
    name:"大白",
    age:23,
    gender:'男',
    c: 23,
    d:'小白'
}

extends 继承

// extends 继承 相当于合并了,a 就得有B的 ‘xxx’属性了
interface Axxsxs extends B {
    name: string
    age: number
}

interface B {
    xxx: string
}

let a: Axxsxs = {
    name: "大白",
    age: 23,
    xxx: '你好',
}

readonly 只读属性, ? 属性可选

interface Axxsxs {
    // 可选属性 使用?操作符
    //加了个问号,就变成可选的
    gender?: string
    // 任意属性 [propName: string]
    [propName: string]: any // 就不会去检验他,如果定义为 string 类型,就所有类型必须为 string
    // readonly 只读属性
    readonly  fn: () => boolean
    readonly id: number
}
let a: Axxsxs = {
    id: 1,
    name: "大白",
    age: 23,
    fn: () => {
        return false
    },
    xxx: '你好',
}

a.fn()

// 因为是只读的,所以报错
a.fn = () => {
    return true
}

```

定义函数

// 定义函数类型
interface  ad{
    (name:string):number[]
}
// 因为接收的是 string 类型的,如果定义为number 是不对的
const cd:ad = function (name:string){
    return [1]
}