对象类型
对象类型只有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 // 冲突,键名匹配,键值不匹配
}
网友评论