TypeScript中继承接口时readonly修饰符无法传递?
TypeScript中readonly接口继承的预期行为及替代方案
我尝试在TypeScript中创建只读接口,测试readonly修饰符能否传递到子类型,示例代码如下:
type JsonDatum = | string | boolean | number | readonly Json[] | Object | null | undefined; interface JsonInterface { readonly [key: string]: Json; } type Json = JsonDatum | JsonInterface; interface Player extends JsonInterface { name: string; countryCodes: number[]; elo: number; } const player: Player = { name: "John Doe", countryCodes: [1, 2, 3], elo: 2000 } player.name = "123" // 无报错 player.countryCodes = [] // 无报错
我原本以为给JsonInterface添加readonly修饰符后,继承它的接口属性也会变为只读,但实际修改操作并未报错。
目前我只能手动给子类型的所有属性添加readonly来实现预期效果:
// 省略重复定义代码 interface Player extends JsonInterface { readonly name: string; readonly countryCodes: number[]; readonly elo: number; } // 省略重复赋值代码 player.name = "123" // 无法分配到'name',因为它是只读属性。(2540) player.countryCodes = [] // 无法分配到'countryCodes',因为它是只读属性。(2540)
我考虑过改用Readonly<T>泛型,但该方案存在问题,且我尝试适配示例时并未成功。
请问这是TypeScript的预期行为吗?有没有不使用Readonly<T>的解决办法?
内容的提问来源于stack exchange,提问作者psygo
相关产品推荐
相关产品推荐

