TypeScript只读属性与方法

TypeScript只读属性与方法,在接口声明中,使用readonly修饰符能够定义只读属性。readonly修饰符只允许在属性签名和索引签名中使用,具体语法如下所示:

readonly PropertyName: Type;

readonly [IndexName: string]: Type
readonly [IndexName: number]: Type

例如,下例的接口A中定义了只读属性a和只读的索引签名:

interface A {
   readonly a: string;
   readonly [prop: string]: string;
   readonly [prop: number]: string;
}

若接口中定义了只读的索引签名,那么接口类型中的所有属性都是只读属性。示例如下:

interface A {
   readonly [prop: string]: number;
}

const a: A = { x: 0 };

a.x = 1; // 编译错误!不允许修改属性值

如果接口中既定义了只读索引签名,又定义了非只读的属性签名,那么非只读的属性签名定义的属性依旧是非只读的,除此之外的所有属性都是只读的。例如,下例的接口A中定义了只读索引签名和非只读属性x。最终的结果为,属性x是非只读的,其余的属性为只读属性。示例如下:

interface A {
   readonly [prop: string]: number;
   x: number;
}

const a: A = { x: 0, y: 0 };

a.x = 1; // 正确
a.y = 1; // 错误

关于只读属性的详细介绍请朋友们参考对象类型字面量

酷客网相关文章:

赞(0)

评论 抢沙发

评论前必须登录!