是否可以更改打字稿中中定义的接口属性的类型?
Is there a way to change the type of interface property defined in a *.d.ts in typescript?
例如: x.d.ts中的接口定义为
for example: An interface in x.d.ts is defined as
interface A { property: number; }我想在我写的打字稿文件中对其进行更改
I want to change it in the typescript files that I write to
interface A { property: Object; }甚至可以正常工作
interface B extends A { property: Object; }这种方法行得通吗?当我在系统上尝试时,它不起作用.只是想确认是否有可能?
Will this approach work? It didn't work when I tried on my system. Just want to confirm if it's even possible?
推荐答案您不能更改现有属性的类型.
You can't change the type of an existing property.
您可以添加属性:
interface A { newProperty: any; }但更改现有类型的类型:
But changing a type of existing one:
interface A { property: any; }导致错误:
后续变量声明必须具有相同的类型.多变的 属性"的类型必须为数字",但此处的类型为任何"
Subsequent variable declarations must have the same type. Variable 'property' must be of type 'number', but here has type 'any'
您当然可以拥有自己的接口,以扩展现有接口.在这种情况下,您可以将类型仅覆盖为兼容类型,例如:
You can of course have your own interface which extends an existing one. In that case, you can override a type only to a compatible type, for example:
interface A { x: string | number; } interface B extends A { x: number; }
顺便说一句,您应该避免使用Object作为类型,而应使用类型any.
By the way, you probably should avoid using Object as a type, instead use the type any.
在any类型的文档中状态:
任何类型都是使用现有JavaScript的强大方法, 允许您在选择过程中逐步选择加入和选择退出类型检查 汇编.您可能希望Object扮演类似的角色,因为它 用其他语言. 但是类型为Object的变量仅允许您 给他们赋值-您不能在上调用任意方法 他们,甚至是实际存在的人:
The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation. You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:
let notSure: any = 4; notSure.ifItExists(); // okay, ifItExists might exist at runtime notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check) let prettySure: Object = 4; prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
更多推荐
覆盖Typescript d.ts文件中定义的接口属性类型
发布评论