对象

作者: 苍老师的眼泪 | 来源:发表于2022-08-25 20:15 被阅读0次

对象类型

对象类型只有3种形式来描述:

  • 匿名形式
function show(obj: {name: string, count: number}) {
    console.log(`${obj.name} has ${obj.count} cars`)
}

const edison = {
    name: 'Edison',
    count: 5
}

show(edison)
  • 接口形式
interface Ojb {
    name: string, 
    count: number
}
function show(obj: Ojb) {
    console.log(`${obj.name} has ${obj.count} cars`)
}

const edison:Ojb = {
    name: 'Edison',
    count: 5
}

show(edison)
  • 类型别名
type Ojb = {
    name: string, 
    count: number
}
function show(obj: Ojb) {
    console.log(`${obj.name} has ${obj.count} cars`)
}

const edison:Ojb = {
    name: 'Edison',
    count: 5
}

show(edison)

只读属性和可选属性

interface Person {
    readonly name: string
    readonly family: {
        member: number
    }
    location: {
        readonly n: number
    }
    alias?: string      // 可选属性
}

let edison: Person = {
    name: 'Edison',
    family: {
        member: 4
    },
    location: {
        n: 10
    }
}

// name 是 readonly 属性,修改它会报错
// edison.name = 'Hsieh'

// 虽然 family 是 readonly 属性,但是可以修改它的属性
edison.family.member +=2


// 虽然 location.n 是 readonly 属性,但是可以修改location属性
edison.location = {
    n: 20
}

索引签名(约束属性名的类型)

// 包含两层意思:
// 1. 如果键名是 number 类型, 则相应的键值一定为 string
// 2. 如果是一个不存在的属性名,这个属性名必须是 number 类型
interface Ojb {
    [props: number]: string
    count: number   // 不冲突,键名类型不匹配
    100: string     // 不冲突,类型匹配
    // 200: number     // 冲突,键名匹配,键值不匹配
}

相关文章

网友评论

      本文标题:对象

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